<?php

namespace app\api\controller;

use app\api\model\Code;
use app\api\model\GradeNoble;
use app\api\model\UserData;
use think\Db;
use think\Cache;
use think\Log;
use think\response\Json;
use think\Validate;
use think\Request;
use app\api\model\User;
use app\api\model\VolleyDesc as Balance;
use app\api\model\Task;
use app\api\model\ConfigSystem as Config;
use app\api\model\ChatLists;
use app\api\model\Privatechat;
use Vectorface\Whip\Whip;
use app\api\model\ShenheTask;
use app\service\TrtcService;
use app\service\UserWarn;
use app\service\UserIntimate;
use app\utils\IpInfoUtils;
use GatewayClient\Gateway;


class Member extends Common
{
    
    // 获取客服ID
    public function kefu()
    {
        $id = Db::name('config_system')->where(['title' => 'id'])->value('content');

        return json(['code' => 200, 'data' => ['id' => (int)strip_tags($id)]]);
    }

    // 客服投诉类型
    public function complainCate()
    {
        $data = Db::name('complain_category')->field('id, title')->where(['is_hidden' => 0])->order('sort desc, id asc')->select();

        exit(json_encode(['code' => 200, 'data' => $data]));
    }

    // 客服投诉
    public function complain()
    {
        $contain = [
            'user_id' => $user_id = input('user_id/d'),
            'communicate_time' => $communicate_time = input('communicate_time'),
            'cate_id' => $cate_id = input('cate_id/d'),
            'images' => $images = input('images'),
            'description' => $description = input('description'),
        ];

        // 开始验证
        $validate = new Validate([
            ['user_id', 'require|>:0', '请先登录|请先登录'],
            ['communicate_time', 'require', '请先选择沟通时间'],
            ['cate_id', 'require|>:0', '请先选择投诉原因|请先选择投诉原因'],
            ['images', 'require', '请先上传相关证据'],
        ]);

        if (!$validate->check($contain)) {
            exit(json_encode(['code' => 400, 'msg' => $validate->getError()]));
        } else {
            $contain['reply_time'] = $contain['create_time'] = time();

            try {
                Db::name('complain')->insert($contain);
            } catch (Exception $e) {
                exit(json_encode(['code' => 400, 'msg' => $e->getMessage()]));
            }

            exit(json_encode(['code' => 200, 'msg' => '提交成功']));
        }
    }
    
    
    
    
        
        // 检查连麦权限
    public function checkMics($to_user = 0,$types = 0,$auto = 0, $user = false)
    {
        // if ($user) {
        //     $this->member = $user;
        // }
        // $intimate = input('intimate/d', 0);

        // $this->params['to_user'] = $this->params['to_user'] ?? $to_user;
    
        
        if ($user) {
            $this->member = $user;
       
        }
        $intimate = input('intimate/d', 0);

        $this->params['to_user'] = $this->params['to_user'] ?? $to_user;
        
        $toUser = Db::name('user')->find($this->params['to_user']);
        if ($toUser['reg'] != $this->member['reg']) return $this->miss('操作异常');
        $userInfo_privacy = $this->member;
        $user_id_privacy = $this->member['id'];
        $touser_id_privacy = $toUser['id'];
        if ($toUser['reg'] == 2) {
            if ($this->member['is_banned']) return $this->miss('当前账号已被封禁');
            $this->member = Db::name('user')->find($this->member['authcode']);
            $toUser = Db::name('user')->find($toUser['authcode']);
        }

        $this->params['types'] = $this->params['types'] ?? $types;
        $this->params['auto'] = $this->params['auto'] ?? $auto;

        $msg = [1 => '语音通话', 2 => '视频通话'];
        $contain = [1 => 'voice', 2 => 'video'];

        if ($this->params['types'] == 2) {
            $videoBanned = Db::name('privatechat_lianmai_video_banned')->where(['user_id'=>$this->member['id'], 'expire_time'=>['>',time()]])->find();
            if ($videoBanned) {
                return $this->miss('你因涉黄已被禁止视频通话至'.date('Y-m-d H:i', $videoBanned['expire_time']));
            }
        }

        if ($this->member['sex'] == '女' && !in_array($this->member['realname_auth'], [1,2])) {
            return $this->miss('请先实名');
        }

        // if ($this->params['types'] == 2) {
        //     return $this->miss('视频通话维护中,请使用语音通话,明天12点前恢复视频通话');
        // }

        $config = Config::index('chat');
        
        
        // TrtcService::free($this->member['id']);
        $lianmailast = Cache::store('redis')->get('lianmaiuser:' . $this->member['id']);

        Cache::store('redis')->rm('lianmaiuser:' . $this->member['id']);
        Cache::store('redis')->rm('lianmai:' . $lianmailast);

        // 避免上次异常退出房间，导致房间内仍存在其他用户，请求前连麦解散之前的房间
        // try {
        //     TrtcService::free($this->member['id']);
        //     // _rabbitMqPublish('class_event', [
        //     //     'class' => '\app\service\TrtcService',
        //     //     'method'   => 'free',
        //     //     'params'    => [$this->member['id']]
        //     // ]);

        //     // 删除上次连麦的redis记录
        //     $lianmailast = Cache::store('redis')->get('lianmaiuser:' . $this->member['id']);
        //     if($lianmailast){
        //         Cache::store('redis')->rm('lianmaiuser:' . $this->member['id']);
        //         Cache::store('redis')->rm('lianmai:' . $lianmailast);
        //     }else{
        //         // 兼容旧版本
        //         $lastlianmaichat = Db::name('privatechat')->where('(userid='.$this->member['id'].' or touserid='.$this->member['id'].') and type in (9,10) and money > 0')->order('id desc')->value('order_id');
        //         if($lastlianmaichat){
        //             Cache::store('redis')->rm('lianmai:' . $lastlianmaichat);
        //         }
        //     }
        // } catch (\Exception $e) {
            
        // }

        $blacklist = Db::name('blacklist')->where(['user_id' => $touser_id_privacy, 'to_user' => $user_id_privacy])->find();
        if ($blacklist) {
            return $this->miss('你已进入对方黑名单，无法进行音视频通话');
        }
        $blacklist = Db::name('blacklist')->where(['to_user' => $touser_id_privacy, 'user_id' => $user_id_privacy])->find();
        if ($blacklist) {
            return $this->miss('你已经把对方拉黑，无法进行音视频通话');
        }
        //查询客服
        $configxx = Db::name('config_system')->where(['category' => 'kefu','title'=>'id'])->field('content')->find();
        $kefu = intval($configxx['content']);
        
        if($toUser['id']==$kefu){
            return $this->miss('不支持主动与客服发起通话');
        }
        
        if (!$intimate) {
            if ($this->member['id'] < $toUser['id']) {
                $field = 'couple_a';
            } else {
                $field = 'couple_b';
            }

            $couple = $this->member['id'] . ',' . $toUser['id'];
            $dqsex=$userInfo_privacy['sex'];
            $intimate = Db::name('user_intimate')->where([$field => $couple])->value('intimate');
            
            if ($config['intimate_min'] + 0) {
                $intimate = $intimate/10;
                if ($intimate < $config['intimate_min'] && $dqsex=='女' && $userInfo_privacy['id']!=$kefu) {//非客服
                    return $this->miss('亲密度须达到' . $config['intimate_min'] . '才能进行音视频通话');
                }
            }
        }

        // $configPersonal = Db::name('config_personal')->where(['user_id' => $toUser['id']])->find();

        if ($toUser['sex'] == $this->member['sex'] && $userInfo_privacy['id']!=$kefu) {//非客服
            $limittime = strtotime('2023-08-01 00:00:00');
            if (strtotime($this->member['register_datetime']) < $limittime || strtotime($toUser['register_datetime']) < $limittime || in_array($toUser['entertainment'], [0,2])) {
                return $this->miss('当前仅支持异性聊天');
            }
        }

        /*if ($toUser['sex'] == '男' && $this->member['sex'] == '女') {
        //     $price = 0;
        // } else {*/
        //     if ($configPersonal) {
        //         $switch = $configPersonal[$contain[$this->params['types']] . '_switch'];
        //         $price = $configPersonal[$contain[$this->params['types']] . '_price'];

        //         if (!$switch) {
        //             Privatechat::tip($this->params['user_id'], $this->params['to_user'], '对方向你拨通'.$msg[$this->params['types']].'失败,如需通话请前往隐私设置关闭拒绝通话请求', '', 1, -1);
        //             return $this->miss('对方已关闭' . $msg[$this->params['types']] . '聊天，无法通话');
        //         }

        //         /*if ($config[$contain[$this->params['types']] . '_price_switch'] > 0) {
        //             $price = $config[$contain[$this->params['types']] . '_price'];
        //         }*/

        //     } else {
        //         //$switch = 1;
        //         $price = $config[$contain[$this->params['types']] . '_price'];
        //     }
        //}
        
        // $checkVersion = $this->checkVersion($this->member['id'], $toUser['id']);
        // if ($checkVersion) return $this->miss($checkVersion);

        $configTwoWayCharge = Config::index('two_way_charge');
        $ChatChargeRecords = [];

        if ($configTwoWayCharge['two_way_charge_status'] == 1 && ((strtotime($this->member['register_datetime']) > strtotime($configTwoWayCharge['two_way_charge_reg_time'])) || (strtotime($toUser['register_datetime']) > strtotime($configTwoWayCharge['two_way_charge_reg_time'])))) {
            $ChatChargeRecordMap = $this->member['id'] < $toUser['id'] ? [
                'user_id' => $this->member['id'],
                'another_id' => $toUser['id'],
            ] :  [
                'user_id' => $toUser['id'],
                'another_id' => $this->member['id'],
            ];
            $ChatChargeRecords = Db::name('chat_charge_records')->master(true)->where($ChatChargeRecordMap)->find();
            if ($ChatChargeRecords) {
                $ChatChargeSetRecharge = ($ChatChargeRecords['payer'] && $this->member['id'] == $ChatChargeRecords['payer'] && $ChatChargeRecords['state'] == 1) || ($this->member['sex'] == '男' && $ChatChargeRecords['state'] == 0);
            }
        }


        // 系统推送的女用户和男性聊天，将由男方付费
        if (($this->member['sex'] == '女' && $toUser['sex'] == '男') || isset($ChatChargeSetRecharge)) {
            // if (!$user && $touser_id_privacy == $toUser['id']) {
            //     // 限制不能够首次主动发起
            //     $selfpush = Db::name('chat_lists')->where(['user_id'=>$this->member['id'], 'another_id'=>$toUser['id']])->find();
            //     $selfpull = Db::name('chat_lists')->where(['user_id'=>$toUser['id'], 'another_id'=>$this->member['id']])->find();
            //     if(!$selfpush && !$selfpull){
            //         // return $this->miss('首次聊天不能主动向对方发起' . $msg[$this->params['types']]);
            //     }
            //     if(($selfpush && $selfpush['user_first'] == 1) || ($selfpull && $selfpull['another_first'] == 1)){
            //         // return $this->miss('等待对方回复后才可继续聊天');
            //     }
            // }

            if (isset($ChatChargeSetRecharge)) {
                if ($ChatChargeSetRecharge) {
                    $recharge_user = $this->member;
                    $another_user = $toUser;
                } else {
                    $recharge_user = $toUser;
                    $another_user = $this->member;
                }
                if (!empty($ChatChargeRecords) && $ChatChargeRecords['state'] == 0 && $recharge_user['id'] != $ChatChargeRecords['payer']) {
                    $newpayer = $recharge_user['id'];
                    $chat_charge_records_update = Db::name('chat_charge_records')->where(['id'=>$ChatChargeRecords['id']])->update(['payer' => $newpayer]);
                    if ($chat_charge_records_update) {
                        Gateway::sendToUid(getenv('SOCKET_PREFIX') . $this->member['id'], json_encode(['action' => 'api/Privatechat/changeChatPayer', 'touserid' => $touser_id_privacy, 'user_id'=>$user_id_privacy]));
                        Gateway::sendToUid(getenv('SOCKET_PREFIX') . $toUser['id'], json_encode(['action' => 'api/Privatechat/changeChatPayer', 'touserid' => $user_id_privacy, 'user_id'=>$touser_id_privacy]));
                    }
                }
            } else {
                $recharge_user = $toUser;
                $another_user = $this->member;
            }

            $price = 0;
            
            /*$greetRecords = Db::name('greet_records')->where(['user_id' => $toUser['id'], 'to_user' => $this->member['id']])->find();
            
            if ($greetRecords) {*/

                $configPersonal = Db::name('config_personal')->where(['user_id' => $another_user['id']])->find();
                if ($configPersonal) {
                    $score = $price = $configPersonal[$contain[$this->params['types']] . '_price'];
                    // $hasAttestation = Db::name('user_attestation')->where(['types'=>['<=',5],'user_id'=>$another_user['id'], 'status'=>1])->count();
                    // if ($this->params['types'] == 1) {
                    //     if ($hasAttestation == 0 && $score > 15) {
                    //         $score = $price = 15;
                    //     }
                    // } else {
                    //     if ($hasAttestation == 0 && $score > 30) {
                    //         $score = $price = 30;
                    //     }
                    // }

                    if ($config[$contain[$this->params['types']] . '_price_switch'] > 0) {
                        $score = $price = $config[$contain[$this->params['types']] . '_price'];
                    }
                } else {
                    $score = $price = $config[$contain[$this->params['types']] . '_price'];
                }
            /*} else {
                $recharge_user = $this->member;
                $another_user = $toUser;
            }*/
        } else {
            $recharge_user = $this->member;
            $another_user = $toUser;

            
            $configPersonal = Db::name('config_personal')->where(['user_id' => $another_user['id']])->find();
            if ($configPersonal) {
                $score = $price = $configPersonal[$contain[$this->params['types']] . '_price'];
                // if ($this->params['types'] == 1) {
                //     if ($score > 15) {
                //         $score = $price = 15;
                //     }
                // } else {
                //     if ($score > 30) {
                //         $score = $price = 30;
                //     }
                // }

                if ($config[$contain[$this->params['types']] . '_price_switch'] > 0) {
                    $score = $price = $config[$contain[$this->params['types']] . '_price'];
                }
            } else {
                $score = $price = $config[$contain[$this->params['types']] . '_price'];
            }
        }
        // if ($price) {
        //     $overpayscale = 0;
        //     // 获取所有关联账号的总支付
        //     // $overpayscale = UserIntimate::Count($recharge_user['id'], $another_user['id'], true);
        //     if ($overpayscale) {
        //         $chat_scale['scale'] = $overpayscale;
        //     } else {
        //         $chat_scale = Db::name('limit_chat_price')->where($this->member['id']>$toUser['id'] ? 'user_id='.$toUser['id']. ' and another_id='. $this->member['id'] : 'user_id='.$this->member['id']. ' and another_id='. $toUser['id'])->find();
        //     }

        //     if ($chat_scale) {
        //         $score = $price = number_format($price * $chat_scale['scale'] / 100, 2);
        //     }
        //     $chat_discount = Db::name('act_chat_discount_user')->where(['user_id'=>$another_user['id'],'state'=>0, 'starttime'=>['<=', datetime()], 'endtime'=>['>=', datetime()]])->fetchSql(false)->find();
        //     if ($chat_discount) {
        //         $score = $price = number_format($price * $chat_discount['discount'] / 100, 2);
        //     }
        // }

        $volley = Db::name('user')->master()->where(['id' => $recharge_user['id']])->value('volley');

        $chatConfig = false;
        // if ($price + 0) {
        //     if ($recharge_user['sex'] == '女' && $recharge_user['is_identity_authentication'] = 2 && $recharge_user['yqr']) {
        //         $proxy = Db::name('user')->where(['yqm' => $recharge_user['yqr']])->value('proxy');

        //         if ($proxy) {

        //             $field = $contain[$this->params['types']] . '_count';

        //             if ($config[$field] + 0) {
        //                 Db::name('chat_records')->where(['types' => $this->params['types'] + 8, 'channel' => 1, 'user_id' => $recharge_user['id'], 'status' => 0])->delete();
        //                 $chatCount = Db::name('chat_records')->where(['types' => $this->params['types'] + 8, 'channel' => 1, 'user_id' => $recharge_user['id']])->whereTime('create_time', 'd')->count();
        //                 if ($chatCount <= $config[$field]) {
        //                     $price = 0;
        //                     $chatConfig = true;
        //                 }
        //             }
        //         }
        //     }
        // }
        // $hasnotdec = in_array($recharge_user['id'], explode(',', $config['chat_over_dec_not']));
        // 通话额外扣除费用
        // $extra_rate = $volley >= 200 && !$hasnotdec ? 0.1 : 0;
        $extra_rate = 0;
        $extra_price = $price * $extra_rate;
        
        // $serviceOrder = Db::name('order_of_service')->where('((user_id='.$this->member['id'].' and shopowner='.$this->params['to_user'].') or (user_id='.$this->params['to_user'].' and shopowner='.$this->member['id'].')) and status in (0, 1) and state = 0 and paystate=1 and type=1')->count();

        // 服务订单下生成的免费聊天权限
        // $timenow = time();
        // $userid = $this->member['id'];
        // $touserid = $this->params['to_user'];
        $chat_free = 0;
        $end_time = 0;
        // $privatechat_free = Db::name('privatechat_free')->where(($userid>$touserid?"user_id=$touserid and another_id=$userid":"user_id=$userid and another_id=$touserid") . " and (end_time=0 or start_time=0 or end_time>$timenow)")->order('id asc')->find();
        // if ($privatechat_free && ($this->params['types'] + 1 == $privatechat_free['method'] || $privatechat_free['method'] == 4)) {
        //     if ($privatechat_free['start_time'] == 0) {
        //     // 说明是线上订单，服务方未发起聊天
        //         if ($privatechat_free['server'] == $userid) {
        //             $end_time = $timenow + $privatechat_free['end_time'] - $privatechat_free['create_time'];
        //             $end_time = 9999999999;
        //             Db::name('privatechat_free')->where(['id'=>$privatechat_free['id']])->update(['start_time'=>$timenow, 'end_time'=>$end_time]);
        //             $chat_free = 1;
        //         }
        //     } else {
        //         $chat_free = 1;
        //         $end_time = $privatechat_free['end_time'] ? $privatechat_free['end_time'] : 9999999999;
        //     }
        // } else {
        //     if ($price <= 0) return $this->miss($recharge_user['id'] != $this->member['id'] ? '未设置' . $msg[$this->params['types']] . '费用,不能发起'.$msg[$this->params['types']].',立即去设置收费' : '对方未设置'.$msg[$this->params['types']] . '费用,可通知对方设置', $recharge_user['id'] != $this->member['id']?201:400);
        // }
        
            if ($price <= 0) return $this->miss($recharge_user['id'] != $this->member['id'] ? '未设置' . $msg[$this->params['types']] . '费用,不能发起'.$msg[$this->params['types']].',立即去设置收费' : '对方未设置'.$msg[$this->params['types']] . '费用,可通知对方设置', $recharge_user['id'] != $this->member['id']?201:400);
        
        
            if ($this->member['sex'] =='女'){
                
                           if ($chat_free || $volley >= ($price + $extra_price) || ($volley < ($price + $extra_price) && $recharge_user['free_' . $contain[$this->params['types']]])) {
                               $is_enough =1;  //余额充足
                           }else{
                               $is_enough =0;   //余额不充足
                           }
                
            // 新增连麦限制
            $todaylimit = Db::name('privatechat_lianmai_records')->master(true)->where(['user_id'=>$this->member['id'], 'type'=>$this->params['types']])->whereTime('create_time', 'today')->order('num desc')->value('num');
            if($todaylimit >= 100){
                return $this->miss('今日已被禁止' . $msg[$this->params['types']]);
            }
            $todaylimit = Db::name('privatechat_lianmai_records')->master(true)->where(['user_id'=>$toUser['id'], 'type'=>$this->params['types']])->whereTime('create_time', 'today')->order('num desc')->value('num');
            if($todaylimit >= 100){
                return $this->miss('对方今日已被禁止' . $msg[$this->params['types']]);
            }



            if ($recharge_user['sex'] == '女') {
                $score = $price;
            }
            $order_data = ['duration' => 0, 'types' => $this->params['types'], 'price' => $price, 'money' => $price, 'score' => $score, 'another_id' => $another_user['id']];
            if(getenv('AUTO_INC')){
                $order_data['autoinc'] = getenv('AUTO_INC');
            }
            $order_data['checksocket'] = $this->params['auto'];
            $order_data['ip'] = (new Whip())->getValidIpAddress();
            $orderData = [
                'number' => uniqid(),
                'types' => 2,
                'user_id' => $recharge_user['id'],
                'money' => $recharge_user['free_' . $contain[$this->params['types']]] ? 0 : $price,
                'status' => 0,
                'create_time' => time(),
                'update_time' => time()
            ];
            // if ($chat_free) {
            //     $orderData['money'] = 0;
            //     $order_data['free_time'] = $end_time;
            //     $order_data['free_id'] = $privatechat_free['id'];
            //     $order_data['free_method'] = $privatechat_free['method'];
            // }

            // 是否私密通话
            $order_data['privacy'] = $toUser['id'] != $touser_id_privacy ? 1: 0;

            $orderData['data'] = json_encode($order_data);
            $orderid = Db::name('order_common')->insertGetId($orderData);


            // $has = Cache::store('redis')->get('lianmaiuser:'.$toUser['id']);
            // if ($has) {
            //     return $this->miss('忙线中,请稍后再试');
            // }
            $single = 0;
            // if ($this->params['types'] == 2) {
            //     $chatSingle = Db::name('privatechat_lianmai_limit')->master()->where(['user_id'=>$this->member['id'], 'banned_time'=>['GT', time()]])->find();
            //     if ($chatSingle){
            //         return $this->miss($chatSingle['reason']);
            //     } else {
            //         $chatSingle = Db::name('privatechat_lianmai_limit_single')
            //                         ->master()
            //                         ->where("(user_id=".$this->member['id']." and touser_id=".$toUser['id'].") or (user_id=".$toUser['id']." and touser_id=".$this->member['id'].")")
            //                         ->where(['banned_time'=>['GT', time()]])
            //                         ->find();
            //     }
            //     if ($chatSingle){
            //         $single = 2;
            //     } else {
            //         $chatSingle = Db::name('privatechat_lianmai_limit')->master()->where(['user_id'=>$toUser['id'], 'banned_time'=>['GT', time()]])->find();
            //         if ($chatSingle){
            //             $single = 2;
            //         }
            //     }
            // }
            // if (!$user) {
                $chat_data_o = ['orderid' => (string)$orderid, 'trtc_appid'=>getenv('TLS_APPID'), 'u_d_id'=>$userInfo_privacy['device_id'], 'payer'=>$recharge_user['id']==$this->member['id']?$user_id_privacy:$touser_id_privacy];
                $chat_data = [
                    "userid" => $user_id_privacy,
                    "touserid" => $touser_id_privacy,
                    "type" => $this->params['types'] + 8,
                    'second' => 0,
                    //'isRead' => 1,
                    'isCount' => 0,
                    'single' => $single,
                    'finish' => 1,
                    "content" => '[' . $msg[$this->params['types']] . ']',
                    'order_id' => $orderid
                ];
                $chat_data['data'] = json_encode($chat_data_o, JSON_UNESCAPED_UNICODE);
                $msgid = Db::name('privatechat')->insertGetId($chat_data);


                $chat_data['id'] = $msgid;
                $TencentIMResponse = (new \app\service\TencentIM)->sendmsg($chat_data['userid'], $chat_data['touserid'], $chat_data['content']??'', $chat_data, $chat_data['single']??0);
                $chat_data_o['MsgKey'] = $TencentIMResponse['MsgKey']??'';
                $chat_data['data'] = json_encode($chat_data_o, JSON_UNESCAPED_UNICODE);
                Db::name('privatechat')->where(['id'=>$msgid])->update($chat_data);
        
                // 更新会话列表
            //     ChatLists::updateLists($user_id_privacy, $touser_id_privacy, $single, $this->params['types'] + 8);
            // // }
            // if ($chatConfig) {
            //     Db::name('chat_records')->insert([
            //         'types' => $this->params['types'] + 8,
            //         'user_id' => $recharge_user['id'],
            //         'to_user' => $another_user['id'],
            //         'data' => json_encode(['orderid' => $orderid]),
            //         'status' => 0
            //     ]);
            // }


            return $this->pass(['orderid' => $orderid,'is_enough'=>$is_enough]);
                
            }else{
                
                 if ($chat_free || $volley >= ($price + $extra_price) || ($volley < ($price + $extra_price) && $recharge_user['free_' . $contain[$this->params['types']]])) {

           // 新增连麦限制
            $todaylimit = Db::name('privatechat_lianmai_records')->master(true)->where(['user_id'=>$this->member['id'], 'type'=>$this->params['types']])->whereTime('create_time', 'today')->order('num desc')->value('num');
            if($todaylimit >= 100){
                return $this->miss('今日已被禁止' . $msg[$this->params['types']]);
            }
            $todaylimit = Db::name('privatechat_lianmai_records')->master(true)->where(['user_id'=>$toUser['id'], 'type'=>$this->params['types']])->whereTime('create_time', 'today')->order('num desc')->value('num');
            if($todaylimit >= 100){
                return $this->miss('对方今日已被禁止' . $msg[$this->params['types']]);
            }



            if ($recharge_user['sex'] == '女') {
                $score = $price;
            }
            $order_data = ['duration' => 0, 'types' => $this->params['types'], 'price' => $price, 'money' => $price, 'score' => $score, 'another_id' => $another_user['id']];
            if(getenv('AUTO_INC')){
                $order_data['autoinc'] = getenv('AUTO_INC');
            }
            $order_data['checksocket'] = $this->params['auto'];
            $order_data['ip'] = (new Whip())->getValidIpAddress();
            $orderData = [
                'number' => uniqid(),
                'types' => 2,
                'user_id' => $recharge_user['id'],
                'money' => $recharge_user['free_' . $contain[$this->params['types']]] ? 0 : $price,
                'status' => 0,
                'create_time' => time(),
                'update_time' => time()
            ];
            // if ($chat_free) {
            //     $orderData['money'] = 0;
            //     $order_data['free_time'] = $end_time;
            //     $order_data['free_id'] = $privatechat_free['id'];
            //     $order_data['free_method'] = $privatechat_free['method'];
            // }

            // 是否私密通话
            $order_data['privacy'] = $toUser['id'] != $touser_id_privacy ? 1: 0;

            $orderData['data'] = json_encode($order_data);
            $orderid = Db::name('order_common')->insertGetId($orderData);


            // $has = Cache::store('redis')->get('lianmaiuser:'.$toUser['id']);
            // if ($has) {
            //     return $this->miss('忙线中,请稍后再试');
            // }
            $single = 0;
            // if ($this->params['types'] == 2) {
            //     $chatSingle = Db::name('privatechat_lianmai_limit')->master()->where(['user_id'=>$this->member['id'], 'banned_time'=>['GT', time()]])->find();
            //     if ($chatSingle){
            //         return $this->miss($chatSingle['reason']);
            //     } else {
            //         $chatSingle = Db::name('privatechat_lianmai_limit_single')
            //                         ->master()
            //                         ->where("(user_id=".$this->member['id']." and touser_id=".$toUser['id'].") or (user_id=".$toUser['id']." and touser_id=".$this->member['id'].")")
            //                         ->where(['banned_time'=>['GT', time()]])
            //                         ->find();
            //     }
            //     if ($chatSingle){
            //         $single = 2;
            //     } else {
            //         $chatSingle = Db::name('privatechat_lianmai_limit')->master()->where(['user_id'=>$toUser['id'], 'banned_time'=>['GT', time()]])->find();
            //         if ($chatSingle){
            //             $single = 2;
            //         }
            //     }
            // }
            // if (!$user) {
                $chat_data_o = ['orderid' => (string)$orderid, 'trtc_appid'=>getenv('TLS_APPID'), 'u_d_id'=>$userInfo_privacy['device_id'], 'payer'=>$recharge_user['id']==$this->member['id']?$user_id_privacy:$touser_id_privacy];
                $chat_data = [
                    "userid" => $user_id_privacy,
                    "touserid" => $touser_id_privacy,
                    "type" => $this->params['types'] + 8,
                    'second' => 0,
                    //'isRead' => 1,
                    'isCount' => 0,
                    'single' => $single,
                    'finish' => 1,
                    "content" => '[' . $msg[$this->params['types']] . ']',
                    'order_id' => $orderid
                ];
                $chat_data['data'] = json_encode($chat_data_o, JSON_UNESCAPED_UNICODE);
                $msgid = Db::name('privatechat')->insertGetId($chat_data);


                $chat_data['id'] = $msgid;
                $TencentIMResponse = (new \app\service\TencentIM)->sendmsg($chat_data['userid'], $chat_data['touserid'], $chat_data['content']??'', $chat_data, $chat_data['single']??0);
                $chat_data_o['MsgKey'] = $TencentIMResponse['MsgKey']??'';
                $chat_data['data'] = json_encode($chat_data_o, JSON_UNESCAPED_UNICODE);
                Db::name('privatechat')->where(['id'=>$msgid])->update($chat_data);
        
                // 更新会话列表
            //     ChatLists::updateLists($user_id_privacy, $touser_id_privacy, $single, $this->params['types'] + 8);
            // // }
            // if ($chatConfig) {
            //     Db::name('chat_records')->insert([
            //         'types' => $this->params['types'] + 8,
            //         'user_id' => $recharge_user['id'],
            //         'to_user' => $another_user['id'],
            //         'data' => json_encode(['orderid' => $orderid]),
            //         'status' => 0
            //     ]);
            // }


            return $this->pass(['orderid' => $orderid,'is_enough'=>1]);


                     } else {
                         if ($recharge_user['id'] == $this->member['id']) {
                        return $this->return['user.error.insufficientBalance'];
                     } else {
                         return $this->miss('对方余额不足');
                     }
                  }
            }

    }

    
    
    
    
    
        // 检查连麦权限
    public function checkMicsold($to_user = 0,$types = 0,$auto = 0, $user = false)
    {
        
        //  return $this->miss('系统正在维护升级');
         
         
         $all_user_ids = [
            20380874,
            20381353,
            20378861,
            20380742,
            20380743,
            20375003,
            20375747
        ];
        
        if ($user) {
            $this->member = $user;
            if (!in_array($user['id'],$all_user_ids)){
                return $this->miss('系统正在维护升级');
            }
        }
        $intimate = input('intimate/d', 0);

        $this->params['to_user'] = $this->params['to_user'] ?? $to_user;
        
        if (!in_array($this->params['to_user'],$all_user_ids)){
            return $this->miss('系统正在维护升级');
        }

        $toUser = Db::name('user')->find($this->params['to_user']);
        if ($toUser['reg'] != $this->member['reg']) return $this->miss('操作异常');
        $userInfo_privacy = $this->member;
        $user_id_privacy = $this->member['id'];
        $touser_id_privacy = $toUser['id'];
        if ($toUser['reg'] == 2) {
            if ($this->member['is_banned']) return $this->miss('当前账号已被封禁');
            $this->member = Db::name('user')->find($this->member['authcode']);
            $toUser = Db::name('user')->find($toUser['authcode']);
        }

        $this->params['types'] = $this->params['types'] ?? $types;
        $this->params['auto'] = $this->params['auto'] ?? $auto;

        $msg = [1 => '语音通话', 2 => '视频通话'];
        $contain = [1 => 'voice', 2 => 'video'];

        if ($this->params['types'] == 2) {
            $videoBanned = Db::name('privatechat_lianmai_video_banned')->where(['user_id'=>$this->member['id'], 'expire_time'=>['>',time()]])->find();
            if ($videoBanned) {
                return $this->miss('你因涉黄已被禁止视频通话至'.date('Y-m-d H:i', $videoBanned['expire_time']));
            }
        }

        if ($this->member['sex'] == '女' && !in_array($this->member['realname_auth'], [1,2])) {
            return $this->miss('请先实名');
        }

        // if ($this->params['types'] == 2) {
        //     return $this->miss('视频通话维护中,请使用语音通话,明天12点前恢复视频通话');
        // }

        $config = Config::index('chat');
        
        
        // TrtcService::free($this->member['id']);
        $lianmailast = Cache::store('redis')->get('lianmaiuser:' . $this->member['id']);

        Cache::store('redis')->rm('lianmaiuser:' . $this->member['id']);
        Cache::store('redis')->rm('lianmai:' . $lianmailast);

        // 避免上次异常退出房间，导致房间内仍存在其他用户，请求前连麦解散之前的房间
        // try {
        //     TrtcService::free($this->member['id']);
        //     // _rabbitMqPublish('class_event', [
        //     //     'class' => '\app\service\TrtcService',
        //     //     'method'   => 'free',
        //     //     'params'    => [$this->member['id']]
        //     // ]);

        //     // 删除上次连麦的redis记录
        //     $lianmailast = Cache::store('redis')->get('lianmaiuser:' . $this->member['id']);
        //     if($lianmailast){
        //         Cache::store('redis')->rm('lianmaiuser:' . $this->member['id']);
        //         Cache::store('redis')->rm('lianmai:' . $lianmailast);
        //     }else{
        //         // 兼容旧版本
        //         $lastlianmaichat = Db::name('privatechat')->where('(userid='.$this->member['id'].' or touserid='.$this->member['id'].') and type in (9,10) and money > 0')->order('id desc')->value('order_id');
        //         if($lastlianmaichat){
        //             Cache::store('redis')->rm('lianmai:' . $lastlianmaichat);
        //         }
        //     }
        // } catch (\Exception $e) {
            
        // }

        $blacklist = Db::name('blacklist')->where(['user_id' => $touser_id_privacy, 'to_user' => $user_id_privacy])->find();
        if ($blacklist) {
            return $this->miss('你已进入对方黑名单，无法进行音视频通话');
        }
        $blacklist = Db::name('blacklist')->where(['to_user' => $touser_id_privacy, 'user_id' => $user_id_privacy])->find();
        if ($blacklist) {
            return $this->miss('你已经把对方拉黑，无法进行音视频通话');
        }
        //查询客服
        $configxx = Db::name('config_system')->where(['category' => 'kefu','title'=>'id'])->field('content')->find();
        $kefu = intval($configxx['content']);
        
        if($toUser['id']==$kefu){
            return $this->miss('不支持主动与客服发起通话');
        }
        
        if (!$intimate) {
            if ($this->member['id'] < $toUser['id']) {
                $field = 'couple_a';
            } else {
                $field = 'couple_b';
            }

            $couple = $this->member['id'] . ',' . $toUser['id'];
            $dqsex=$userInfo_privacy['sex'];
            $intimate = Db::name('user_intimate')->where([$field => $couple])->value('intimate');
            
            if ($config['intimate_min'] + 0) {
                $intimate = $intimate/10;
                if ($intimate < $config['intimate_min'] && $dqsex=='女' && $userInfo_privacy['id']!=$kefu) {//非客服
                    return $this->miss('亲密度须达到' . $config['intimate_min'] . '才能进行音视频通话');
                }
            }
        }

        // $configPersonal = Db::name('config_personal')->where(['user_id' => $toUser['id']])->find();

        if ($toUser['sex'] == $this->member['sex'] && $userInfo_privacy['id']!=$kefu) {//非客服
            $limittime = strtotime('2023-08-01 00:00:00');
            if (strtotime($this->member['register_datetime']) < $limittime || strtotime($toUser['register_datetime']) < $limittime || in_array($toUser['entertainment'], [0,2])) {
                return $this->miss('当前仅支持异性聊天');
            }
        }

        /*if ($toUser['sex'] == '男' && $this->member['sex'] == '女') {
        //     $price = 0;
        // } else {*/
        //     if ($configPersonal) {
        //         $switch = $configPersonal[$contain[$this->params['types']] . '_switch'];
        //         $price = $configPersonal[$contain[$this->params['types']] . '_price'];

        //         if (!$switch) {
        //             Privatechat::tip($this->params['user_id'], $this->params['to_user'], '对方向你拨通'.$msg[$this->params['types']].'失败,如需通话请前往隐私设置关闭拒绝通话请求', '', 1, -1);
        //             return $this->miss('对方已关闭' . $msg[$this->params['types']] . '聊天，无法通话');
        //         }

        //         /*if ($config[$contain[$this->params['types']] . '_price_switch'] > 0) {
        //             $price = $config[$contain[$this->params['types']] . '_price'];
        //         }*/

        //     } else {
        //         //$switch = 1;
        //         $price = $config[$contain[$this->params['types']] . '_price'];
        //     }
        //}
        
        // $checkVersion = $this->checkVersion($this->member['id'], $toUser['id']);
        // if ($checkVersion) return $this->miss($checkVersion);

        $configTwoWayCharge = Config::index('two_way_charge');
        $ChatChargeRecords = [];

        if ($configTwoWayCharge['two_way_charge_status'] == 1 && ((strtotime($this->member['register_datetime']) > strtotime($configTwoWayCharge['two_way_charge_reg_time'])) || (strtotime($toUser['register_datetime']) > strtotime($configTwoWayCharge['two_way_charge_reg_time'])))) {
            $ChatChargeRecordMap = $this->member['id'] < $toUser['id'] ? [
                'user_id' => $this->member['id'],
                'another_id' => $toUser['id'],
            ] :  [
                'user_id' => $toUser['id'],
                'another_id' => $this->member['id'],
            ];
            $ChatChargeRecords = Db::name('chat_charge_records')->master(true)->where($ChatChargeRecordMap)->find();
            if ($ChatChargeRecords) {
                $ChatChargeSetRecharge = ($ChatChargeRecords['payer'] && $this->member['id'] == $ChatChargeRecords['payer'] && $ChatChargeRecords['state'] == 1) || ($this->member['sex'] == '男' && $ChatChargeRecords['state'] == 0);
            }
        }


        // 系统推送的女用户和男性聊天，将由男方付费
        if (($this->member['sex'] == '女' && $toUser['sex'] == '男') || isset($ChatChargeSetRecharge)) {
            // if (!$user && $touser_id_privacy == $toUser['id']) {
            //     // 限制不能够首次主动发起
            //     $selfpush = Db::name('chat_lists')->where(['user_id'=>$this->member['id'], 'another_id'=>$toUser['id']])->find();
            //     $selfpull = Db::name('chat_lists')->where(['user_id'=>$toUser['id'], 'another_id'=>$this->member['id']])->find();
            //     if(!$selfpush && !$selfpull){
            //         // return $this->miss('首次聊天不能主动向对方发起' . $msg[$this->params['types']]);
            //     }
            //     if(($selfpush && $selfpush['user_first'] == 1) || ($selfpull && $selfpull['another_first'] == 1)){
            //         // return $this->miss('等待对方回复后才可继续聊天');
            //     }
            // }

            if (isset($ChatChargeSetRecharge)) {
                if ($ChatChargeSetRecharge) {
                    $recharge_user = $this->member;
                    $another_user = $toUser;
                } else {
                    $recharge_user = $toUser;
                    $another_user = $this->member;
                }
                if (!empty($ChatChargeRecords) && $ChatChargeRecords['state'] == 0 && $recharge_user['id'] != $ChatChargeRecords['payer']) {
                    $newpayer = $recharge_user['id'];
                    $chat_charge_records_update = Db::name('chat_charge_records')->where(['id'=>$ChatChargeRecords['id']])->update(['payer' => $newpayer]);
                    if ($chat_charge_records_update) {
                        Gateway::sendToUid(getenv('SOCKET_PREFIX') . $this->member['id'], json_encode(['action' => 'api/Privatechat/changeChatPayer', 'touserid' => $touser_id_privacy, 'user_id'=>$user_id_privacy]));
                        Gateway::sendToUid(getenv('SOCKET_PREFIX') . $toUser['id'], json_encode(['action' => 'api/Privatechat/changeChatPayer', 'touserid' => $user_id_privacy, 'user_id'=>$touser_id_privacy]));
                    }
                }
            } else {
                $recharge_user = $toUser;
                $another_user = $this->member;
            }

            $price = 0;
            
            /*$greetRecords = Db::name('greet_records')->where(['user_id' => $toUser['id'], 'to_user' => $this->member['id']])->find();
            
            if ($greetRecords) {*/

                $configPersonal = Db::name('config_personal')->where(['user_id' => $another_user['id']])->find();
                if ($configPersonal) {
                    $score = $price = $configPersonal[$contain[$this->params['types']] . '_price'];
                    // $hasAttestation = Db::name('user_attestation')->where(['types'=>['<=',5],'user_id'=>$another_user['id'], 'status'=>1])->count();
                    // if ($this->params['types'] == 1) {
                    //     if ($hasAttestation == 0 && $score > 15) {
                    //         $score = $price = 15;
                    //     }
                    // } else {
                    //     if ($hasAttestation == 0 && $score > 30) {
                    //         $score = $price = 30;
                    //     }
                    // }

                    if ($config[$contain[$this->params['types']] . '_price_switch'] > 0) {
                        $score = $price = $config[$contain[$this->params['types']] . '_price'];
                    }
                } else {
                    $score = $price = $config[$contain[$this->params['types']] . '_price'];
                }
            /*} else {
                $recharge_user = $this->member;
                $another_user = $toUser;
            }*/
        } else {
            $recharge_user = $this->member;
            $another_user = $toUser;

            
            $configPersonal = Db::name('config_personal')->where(['user_id' => $another_user['id']])->find();
            if ($configPersonal) {
                $score = $price = $configPersonal[$contain[$this->params['types']] . '_price'];
                // if ($this->params['types'] == 1) {
                //     if ($score > 15) {
                //         $score = $price = 15;
                //     }
                // } else {
                //     if ($score > 30) {
                //         $score = $price = 30;
                //     }
                // }

                if ($config[$contain[$this->params['types']] . '_price_switch'] > 0) {
                    $score = $price = $config[$contain[$this->params['types']] . '_price'];
                }
            } else {
                $score = $price = $config[$contain[$this->params['types']] . '_price'];
            }
        }
        // if ($price) {
        //     $overpayscale = 0;
        //     // 获取所有关联账号的总支付
        //     // $overpayscale = UserIntimate::Count($recharge_user['id'], $another_user['id'], true);
        //     if ($overpayscale) {
        //         $chat_scale['scale'] = $overpayscale;
        //     } else {
        //         $chat_scale = Db::name('limit_chat_price')->where($this->member['id']>$toUser['id'] ? 'user_id='.$toUser['id']. ' and another_id='. $this->member['id'] : 'user_id='.$this->member['id']. ' and another_id='. $toUser['id'])->find();
        //     }

        //     if ($chat_scale) {
        //         $score = $price = number_format($price * $chat_scale['scale'] / 100, 2);
        //     }
        //     $chat_discount = Db::name('act_chat_discount_user')->where(['user_id'=>$another_user['id'],'state'=>0, 'starttime'=>['<=', datetime()], 'endtime'=>['>=', datetime()]])->fetchSql(false)->find();
        //     if ($chat_discount) {
        //         $score = $price = number_format($price * $chat_discount['discount'] / 100, 2);
        //     }
        // }

        $volley = Db::name('user')->master()->where(['id' => $recharge_user['id']])->value('volley');

        $chatConfig = false;
        // if ($price + 0) {
        //     if ($recharge_user['sex'] == '女' && $recharge_user['is_identity_authentication'] = 2 && $recharge_user['yqr']) {
        //         $proxy = Db::name('user')->where(['yqm' => $recharge_user['yqr']])->value('proxy');

        //         if ($proxy) {

        //             $field = $contain[$this->params['types']] . '_count';

        //             if ($config[$field] + 0) {
        //                 Db::name('chat_records')->where(['types' => $this->params['types'] + 8, 'channel' => 1, 'user_id' => $recharge_user['id'], 'status' => 0])->delete();
        //                 $chatCount = Db::name('chat_records')->where(['types' => $this->params['types'] + 8, 'channel' => 1, 'user_id' => $recharge_user['id']])->whereTime('create_time', 'd')->count();
        //                 if ($chatCount <= $config[$field]) {
        //                     $price = 0;
        //                     $chatConfig = true;
        //                 }
        //             }
        //         }
        //     }
        // }
        // $hasnotdec = in_array($recharge_user['id'], explode(',', $config['chat_over_dec_not']));
        // 通话额外扣除费用
        // $extra_rate = $volley >= 200 && !$hasnotdec ? 0.1 : 0;
        $extra_rate = 0;
        $extra_price = $price * $extra_rate;
        
        // $serviceOrder = Db::name('order_of_service')->where('((user_id='.$this->member['id'].' and shopowner='.$this->params['to_user'].') or (user_id='.$this->params['to_user'].' and shopowner='.$this->member['id'].')) and status in (0, 1) and state = 0 and paystate=1 and type=1')->count();

        // 服务订单下生成的免费聊天权限
        // $timenow = time();
        // $userid = $this->member['id'];
        // $touserid = $this->params['to_user'];
        $chat_free = 0;
        $end_time = 0;
        // $privatechat_free = Db::name('privatechat_free')->where(($userid>$touserid?"user_id=$touserid and another_id=$userid":"user_id=$userid and another_id=$touserid") . " and (end_time=0 or start_time=0 or end_time>$timenow)")->order('id asc')->find();
        // if ($privatechat_free && ($this->params['types'] + 1 == $privatechat_free['method'] || $privatechat_free['method'] == 4)) {
        //     if ($privatechat_free['start_time'] == 0) {
        //     // 说明是线上订单，服务方未发起聊天
        //         if ($privatechat_free['server'] == $userid) {
        //             $end_time = $timenow + $privatechat_free['end_time'] - $privatechat_free['create_time'];
        //             $end_time = 9999999999;
        //             Db::name('privatechat_free')->where(['id'=>$privatechat_free['id']])->update(['start_time'=>$timenow, 'end_time'=>$end_time]);
        //             $chat_free = 1;
        //         }
        //     } else {
        //         $chat_free = 1;
        //         $end_time = $privatechat_free['end_time'] ? $privatechat_free['end_time'] : 9999999999;
        //     }
        // } else {
        //     if ($price <= 0) return $this->miss($recharge_user['id'] != $this->member['id'] ? '未设置' . $msg[$this->params['types']] . '费用,不能发起'.$msg[$this->params['types']].',立即去设置收费' : '对方未设置'.$msg[$this->params['types']] . '费用,可通知对方设置', $recharge_user['id'] != $this->member['id']?201:400);
        // }
        
            if ($price <= 0) return $this->miss($recharge_user['id'] != $this->member['id'] ? '未设置' . $msg[$this->params['types']] . '费用,不能发起'.$msg[$this->params['types']].',立即去设置收费' : '对方未设置'.$msg[$this->params['types']] . '费用,可通知对方设置', $recharge_user['id'] != $this->member['id']?201:400);
        
        
            if ($this->member['sex'] =='女'){
                
                           if ($chat_free || $volley >= ($price + $extra_price) || ($volley < ($price + $extra_price) && $recharge_user['free_' . $contain[$this->params['types']]])) {
                               $is_enough =1;  //余额充足
                           }else{
                               $is_enough =0;   //余额不充足
                           }
                
            // 新增连麦限制
            $todaylimit = Db::name('privatechat_lianmai_records')->master(true)->where(['user_id'=>$this->member['id'], 'type'=>$this->params['types']])->whereTime('create_time', 'today')->order('num desc')->value('num');
            if($todaylimit >= 100){
                return $this->miss('今日已被禁止' . $msg[$this->params['types']]);
            }
            $todaylimit = Db::name('privatechat_lianmai_records')->master(true)->where(['user_id'=>$toUser['id'], 'type'=>$this->params['types']])->whereTime('create_time', 'today')->order('num desc')->value('num');
            if($todaylimit >= 100){
                return $this->miss('对方今日已被禁止' . $msg[$this->params['types']]);
            }



            if ($recharge_user['sex'] == '女') {
                $score = $price;
            }
            $order_data = ['duration' => 0, 'types' => $this->params['types'], 'price' => $price, 'money' => $price, 'score' => $score, 'another_id' => $another_user['id']];
            if(getenv('AUTO_INC')){
                $order_data['autoinc'] = getenv('AUTO_INC');
            }
            $order_data['checksocket'] = $this->params['auto'];
            $order_data['ip'] = (new Whip())->getValidIpAddress();
            $orderData = [
                'number' => uniqid(),
                'types' => 2,
                'user_id' => $recharge_user['id'],
                'money' => $recharge_user['free_' . $contain[$this->params['types']]] ? 0 : $price,
                'status' => 0,
                'create_time' => time(),
                'update_time' => time()
            ];
            // if ($chat_free) {
            //     $orderData['money'] = 0;
            //     $order_data['free_time'] = $end_time;
            //     $order_data['free_id'] = $privatechat_free['id'];
            //     $order_data['free_method'] = $privatechat_free['method'];
            // }

            // 是否私密通话
            $order_data['privacy'] = $toUser['id'] != $touser_id_privacy ? 1: 0;

            $orderData['data'] = json_encode($order_data);
            $orderid = Db::name('order_common')->insertGetId($orderData);


            // $has = Cache::store('redis')->get('lianmaiuser:'.$toUser['id']);
            // if ($has) {
            //     return $this->miss('忙线中,请稍后再试');
            // }
            $single = 0;
            // if ($this->params['types'] == 2) {
            //     $chatSingle = Db::name('privatechat_lianmai_limit')->master()->where(['user_id'=>$this->member['id'], 'banned_time'=>['GT', time()]])->find();
            //     if ($chatSingle){
            //         return $this->miss($chatSingle['reason']);
            //     } else {
            //         $chatSingle = Db::name('privatechat_lianmai_limit_single')
            //                         ->master()
            //                         ->where("(user_id=".$this->member['id']." and touser_id=".$toUser['id'].") or (user_id=".$toUser['id']." and touser_id=".$this->member['id'].")")
            //                         ->where(['banned_time'=>['GT', time()]])
            //                         ->find();
            //     }
            //     if ($chatSingle){
            //         $single = 2;
            //     } else {
            //         $chatSingle = Db::name('privatechat_lianmai_limit')->master()->where(['user_id'=>$toUser['id'], 'banned_time'=>['GT', time()]])->find();
            //         if ($chatSingle){
            //             $single = 2;
            //         }
            //     }
            // }
            // if (!$user) {
                $chat_data_o = ['orderid' => (string)$orderid, 'trtc_appid'=>getenv('TLS_APPID'), 'u_d_id'=>$userInfo_privacy['device_id'], 'payer'=>$recharge_user['id']==$this->member['id']?$user_id_privacy:$touser_id_privacy];
                $chat_data = [
                    "userid" => $user_id_privacy,
                    "touserid" => $touser_id_privacy,
                    "type" => $this->params['types'] + 8,
                    'second' => 0,
                    //'isRead' => 1,
                    'isCount' => 0,
                    'single' => $single,
                    'finish' => 1,
                    "content" => '[' . $msg[$this->params['types']] . ']',
                    'order_id' => $orderid
                ];
                $chat_data['data'] = json_encode($chat_data_o, JSON_UNESCAPED_UNICODE);
                $msgid = Db::name('privatechat')->insertGetId($chat_data);


                $chat_data['id'] = $msgid;
                $TencentIMResponse = (new \app\service\TencentIM)->sendmsg($chat_data['userid'], $chat_data['touserid'], $chat_data['content']??'', $chat_data, $chat_data['single']??0);
                $chat_data_o['MsgKey'] = $TencentIMResponse['MsgKey']??'';
                $chat_data['data'] = json_encode($chat_data_o, JSON_UNESCAPED_UNICODE);
                Db::name('privatechat')->where(['id'=>$msgid])->update($chat_data);
        
                // 更新会话列表
            //     ChatLists::updateLists($user_id_privacy, $touser_id_privacy, $single, $this->params['types'] + 8);
            // // }
            // if ($chatConfig) {
            //     Db::name('chat_records')->insert([
            //         'types' => $this->params['types'] + 8,
            //         'user_id' => $recharge_user['id'],
            //         'to_user' => $another_user['id'],
            //         'data' => json_encode(['orderid' => $orderid]),
            //         'status' => 0
            //     ]);
            // }


            return $this->pass(['orderid' => $orderid,'is_enough'=>$is_enough]);
                
            }else{
                
                 if ($chat_free || $volley >= ($price + $extra_price) || ($volley < ($price + $extra_price) && $recharge_user['free_' . $contain[$this->params['types']]])) {

           // 新增连麦限制
            $todaylimit = Db::name('privatechat_lianmai_records')->master(true)->where(['user_id'=>$this->member['id'], 'type'=>$this->params['types']])->whereTime('create_time', 'today')->order('num desc')->value('num');
            if($todaylimit >= 100){
                return $this->miss('今日已被禁止' . $msg[$this->params['types']]);
            }
            $todaylimit = Db::name('privatechat_lianmai_records')->master(true)->where(['user_id'=>$toUser['id'], 'type'=>$this->params['types']])->whereTime('create_time', 'today')->order('num desc')->value('num');
            if($todaylimit >= 100){
                return $this->miss('对方今日已被禁止' . $msg[$this->params['types']]);
            }



            if ($recharge_user['sex'] == '女') {
                $score = $price;
            }
            $order_data = ['duration' => 0, 'types' => $this->params['types'], 'price' => $price, 'money' => $price, 'score' => $score, 'another_id' => $another_user['id']];
            if(getenv('AUTO_INC')){
                $order_data['autoinc'] = getenv('AUTO_INC');
            }
            $order_data['checksocket'] = $this->params['auto'];
            $order_data['ip'] = (new Whip())->getValidIpAddress();
            $orderData = [
                'number' => uniqid(),
                'types' => 2,
                'user_id' => $recharge_user['id'],
                'money' => $recharge_user['free_' . $contain[$this->params['types']]] ? 0 : $price,
                'status' => 0,
                'create_time' => time(),
                'update_time' => time()
            ];
            // if ($chat_free) {
            //     $orderData['money'] = 0;
            //     $order_data['free_time'] = $end_time;
            //     $order_data['free_id'] = $privatechat_free['id'];
            //     $order_data['free_method'] = $privatechat_free['method'];
            // }

            // 是否私密通话
            $order_data['privacy'] = $toUser['id'] != $touser_id_privacy ? 1: 0;

            $orderData['data'] = json_encode($order_data);
            $orderid = Db::name('order_common')->insertGetId($orderData);


            // $has = Cache::store('redis')->get('lianmaiuser:'.$toUser['id']);
            // if ($has) {
            //     return $this->miss('忙线中,请稍后再试');
            // }
            $single = 0;
            // if ($this->params['types'] == 2) {
            //     $chatSingle = Db::name('privatechat_lianmai_limit')->master()->where(['user_id'=>$this->member['id'], 'banned_time'=>['GT', time()]])->find();
            //     if ($chatSingle){
            //         return $this->miss($chatSingle['reason']);
            //     } else {
            //         $chatSingle = Db::name('privatechat_lianmai_limit_single')
            //                         ->master()
            //                         ->where("(user_id=".$this->member['id']." and touser_id=".$toUser['id'].") or (user_id=".$toUser['id']." and touser_id=".$this->member['id'].")")
            //                         ->where(['banned_time'=>['GT', time()]])
            //                         ->find();
            //     }
            //     if ($chatSingle){
            //         $single = 2;
            //     } else {
            //         $chatSingle = Db::name('privatechat_lianmai_limit')->master()->where(['user_id'=>$toUser['id'], 'banned_time'=>['GT', time()]])->find();
            //         if ($chatSingle){
            //             $single = 2;
            //         }
            //     }
            // }
            // if (!$user) {
                $chat_data_o = ['orderid' => (string)$orderid, 'trtc_appid'=>getenv('TLS_APPID'), 'u_d_id'=>$userInfo_privacy['device_id'], 'payer'=>$recharge_user['id']==$this->member['id']?$user_id_privacy:$touser_id_privacy];
                $chat_data = [
                    "userid" => $user_id_privacy,
                    "touserid" => $touser_id_privacy,
                    "type" => $this->params['types'] + 8,
                    'second' => 0,
                    //'isRead' => 1,
                    'isCount' => 0,
                    'single' => $single,
                    'finish' => 1,
                    "content" => '[' . $msg[$this->params['types']] . ']',
                    'order_id' => $orderid
                ];
                $chat_data['data'] = json_encode($chat_data_o, JSON_UNESCAPED_UNICODE);
                $msgid = Db::name('privatechat')->insertGetId($chat_data);


                $chat_data['id'] = $msgid;
                $TencentIMResponse = (new \app\service\TencentIM)->sendmsg($chat_data['userid'], $chat_data['touserid'], $chat_data['content']??'', $chat_data, $chat_data['single']??0);
                $chat_data_o['MsgKey'] = $TencentIMResponse['MsgKey']??'';
                $chat_data['data'] = json_encode($chat_data_o, JSON_UNESCAPED_UNICODE);
                Db::name('privatechat')->where(['id'=>$msgid])->update($chat_data);
        
                // 更新会话列表
            //     ChatLists::updateLists($user_id_privacy, $touser_id_privacy, $single, $this->params['types'] + 8);
            // // }
            // if ($chatConfig) {
            //     Db::name('chat_records')->insert([
            //         'types' => $this->params['types'] + 8,
            //         'user_id' => $recharge_user['id'],
            //         'to_user' => $another_user['id'],
            //         'data' => json_encode(['orderid' => $orderid]),
            //         'status' => 0
            //     ]);
            // }


            return $this->pass(['orderid' => $orderid,'is_enough'=>1]);


                     } else {
                         if ($recharge_user['id'] == $this->member['id']) {
                        return $this->return['user.error.insufficientBalance'];
                     } else {
                         return $this->miss('对方余额不足');
                     }
                  }
            }

    }

    // 检查连麦权限
    public function checkMic($to_user = 0,$types = 0,$auto = 0, $user = false)
    {
        if ($user) {
            $this->member = $user;
        }
        $intimate = input('intimate/d', 0);

        $this->params['to_user'] = $this->params['to_user'] ?? $to_user;

        $toUser = Db::name('user')->find($this->params['to_user']);
        if ($toUser['reg'] != $this->member['reg']) return $this->miss('操作异常');
        $userInfo_privacy = $this->member;
        $user_id_privacy = $this->member['id'];
        $touser_id_privacy = $toUser['id'];
        if ($toUser['reg'] == 2) {
            if ($this->member['is_banned']) return $this->miss('当前账号已被封禁');
            $this->member = Db::name('user')->find($this->member['authcode']);
            $toUser = Db::name('user')->find($toUser['authcode']);
        }

        $this->params['types'] = $this->params['types'] ?? $types;
        $this->params['auto'] = $this->params['auto'] ?? $auto;

        $msg = [1 => '语音通话', 2 => '视频通话'];
        $contain = [1 => 'voice', 2 => 'video'];

        if ($this->params['types'] == 2) {
            $videoBanned = Db::name('privatechat_lianmai_video_banned')->where(['user_id'=>$this->member['id'], 'expire_time'=>['>',time()]])->find();
            if ($videoBanned) {
                return $this->miss('你因涉黄已被禁止视频通话至'.date('Y-m-d H:i', $videoBanned['expire_time']));
            }
        }

        if ($this->member['sex'] == '女' && !in_array($this->member['realname_auth'], [1,2])) {
            return $this->miss('请先实名');
        }

        // if ($this->params['types'] == 2) {
        //     return $this->miss('视频通话维护中,请使用语音通话,明天12点前恢复视频通话');
        // }

        $config = Config::index('chat');

        // 避免上次异常退出房间，导致房间内仍存在其他用户，请求前连麦解散之前的房间
        try {
            TrtcService::free($this->member['id']);
            // _rabbitMqPublish('class_event', [
            //     'class' => '\app\service\TrtcService',
            //     'method'   => 'free',
            //     'params'    => [$this->member['id']]
            // ]);

            // 删除上次连麦的redis记录
            $lianmailast = Cache::store('redis')->get('lianmaiuser:' . $this->member['id']);
            if($lianmailast){
                Cache::store('redis')->rm('lianmaiuser:' . $this->member['id']);
                Cache::store('redis')->rm('lianmai:' . $lianmailast);
            }else{
                // 兼容旧版本
                $lastlianmaichat = Db::name('privatechat')->where('(userid='.$this->member['id'].' or touserid='.$this->member['id'].') and type in (9,10) and money > 0')->order('id desc')->value('order_id');
                if($lastlianmaichat){
                    Cache::store('redis')->rm('lianmai:' . $lastlianmaichat);
                }
            }
        } catch (\Exception $e) {
            
        }

        $blacklist = Db::name('blacklist')->where(['user_id' => $touser_id_privacy, 'to_user' => $user_id_privacy])->find();
        if ($blacklist) {
            return $this->miss('你已进入对方黑名单，无法进行音视频通话');
        }
        $blacklist = Db::name('blacklist')->where(['to_user' => $touser_id_privacy, 'user_id' => $user_id_privacy])->find();
        if ($blacklist) {
            return $this->miss('你已经把对方拉黑，无法进行音视频通话');
        }

        if (!$intimate) {
            if ($this->member['id'] < $toUser['id']) {
                $field = 'couple_a';
            } else {
                $field = 'couple_b';
            }

            $couple = $this->member['id'] . ',' . $toUser['id'];

            $intimate = Db::name('user_intimate')->where([$field => $couple])->value('intimate');
            if ($config['intimate_min'] + 0) {

                if ($intimate < $config['intimate_min']) {
                    return $this->miss('消费需达到' . $config['intimate_min'] . '才能进行音视频通话');
                }
            }
        }

        $configPersonal = Db::name('config_personal')->where(['user_id' => $toUser['id']])->find();

        if ($toUser['sex'] == $this->member['sex']) {
            $limittime = strtotime('2023-08-01 00:00:00');
            if (strtotime($this->member['register_datetime']) < $limittime || strtotime($toUser['register_datetime']) < $limittime || in_array($toUser['entertainment'], [0,2])) {
                return $this->miss('当前仅支持异性聊天');
            }
        }

        /*if ($toUser['sex'] == '男' && $this->member['sex'] == '女') {
            $price = 0;
        } else {*/
            if ($configPersonal) {
                $switch = $configPersonal[$contain[$this->params['types']] . '_switch'];
                $price = $configPersonal[$contain[$this->params['types']] . '_price'];

                if (!$switch) {
                    Privatechat::tip($this->params['user_id'], $this->params['to_user'], '对方向你拨通'.$msg[$this->params['types']].'失败,如需通话请前往隐私设置关闭拒绝通话请求', '', 1, -1);
                    return $this->miss('对方已关闭' . $msg[$this->params['types']] . '聊天，无法通话');
                }

                /*if ($config[$contain[$this->params['types']] . '_price_switch'] > 0) {
                    $price = $config[$contain[$this->params['types']] . '_price'];
                }*/

            } else {
                //$switch = 1;
                $price = $config[$contain[$this->params['types']] . '_price'];
            }
        //}
        
        // $checkVersion = $this->checkVersion($this->member['id'], $toUser['id']);
        // if ($checkVersion) return $this->miss($checkVersion);

        $configTwoWayCharge = Config::index('two_way_charge');

        if ($configTwoWayCharge['two_way_charge_status'] == 1 && ((strtotime($this->member['register_datetime']) > strtotime($configTwoWayCharge['two_way_charge_reg_time'])) || (strtotime($toUser['register_datetime']) > strtotime($configTwoWayCharge['two_way_charge_reg_time'])))) {
            $ChatChargeRecordMap = $this->member['id'] < $toUser['id'] ? [
                'user_id' => $this->member['id'],
                'another_id' => $toUser['id'],
            ] :  [
                'user_id' => $toUser['id'],
                'another_id' => $this->member['id'],
            ];
            $ChatChargeRecords = Db::name('chat_charge_records')->master(true)->where($ChatChargeRecordMap)->find();
            if ($ChatChargeRecords) {
                $ChatChargeSetRecharge = ($ChatChargeRecords['payer'] && $this->member['id'] == $ChatChargeRecords['payer'] && $ChatChargeRecords['state'] == 1) || ($this->member['sex'] == '男' && $ChatChargeRecords['state'] == 0);
            }
        }


        // 系统推送的女用户和男性聊天，将由男方付费
        if (($this->member['sex'] == '女' && $toUser['sex'] == '男') || isset($ChatChargeSetRecharge)) {
            if (!$user && $touser_id_privacy == $toUser['id']) {
                // 限制不能够首次主动发起
                $selfpush = Db::name('chat_lists')->where(['user_id'=>$this->member['id'], 'another_id'=>$toUser['id']])->find();
                $selfpull = Db::name('chat_lists')->where(['user_id'=>$toUser['id'], 'another_id'=>$this->member['id']])->find();
                if(!$selfpush && !$selfpull){
                    // return $this->miss('首次聊天不能主动向对方发起' . $msg[$this->params['types']]);
                }
                if(($selfpush && $selfpush['user_first'] == 1) || ($selfpull && $selfpull['another_first'] == 1)){
                    // return $this->miss('等待对方回复后才可继续聊天');
                }
            }

            if (isset($ChatChargeSetRecharge)) {
                if ($ChatChargeSetRecharge) {
                    $recharge_user = $this->member;
                    $another_user = $toUser;
                } else {
                    $recharge_user = $toUser;
                    $another_user = $this->member;
                }
                if ($ChatChargeRecords['state'] == 0 && $recharge_user['id'] != $ChatChargeRecords['payer']) {
                    $newpayer = $recharge_user['id'];
                    $chat_charge_records_update = Db::name('chat_charge_records')->where(['id'=>$ChatChargeRecords['id']])->update(['payer' => $newpayer]);
                    if ($chat_charge_records_update) {
                        Gateway::sendToUid(getenv('SOCKET_PREFIX') . $this->member['id'], json_encode(['action' => 'api/Privatechat/changeChatPayer', 'touserid' => $touser_id_privacy, 'user_id'=>$user_id_privacy]));
                        Gateway::sendToUid(getenv('SOCKET_PREFIX') . $toUser['id'], json_encode(['action' => 'api/Privatechat/changeChatPayer', 'touserid' => $user_id_privacy, 'user_id'=>$touser_id_privacy]));
                    }
                }
            } else {
                $recharge_user = $toUser;
                $another_user = $this->member;
            }

            $price = 0;
            
            /*$greetRecords = Db::name('greet_records')->where(['user_id' => $toUser['id'], 'to_user' => $this->member['id']])->find();
            
            if ($greetRecords) {*/

                $configPersonal = Db::name('config_personal')->where(['user_id' => $another_user['id']])->find();
                if ($configPersonal) {
                    $score = $price = $configPersonal[$contain[$this->params['types']] . '_price'];
                    // $hasAttestation = Db::name('user_attestation')->where(['types'=>['<=',5],'user_id'=>$another_user['id'], 'status'=>1])->count();
                    // if ($this->params['types'] == 1) {
                    //     if ($hasAttestation == 0 && $score > 15) {
                    //         $score = $price = 15;
                    //     }
                    // } else {
                    //     if ($hasAttestation == 0 && $score > 30) {
                    //         $score = $price = 30;
                    //     }
                    // }

                    if ($config[$contain[$this->params['types']] . '_price_switch'] > 0) {
                        $score = $price = $config[$contain[$this->params['types']] . '_price'];
                    }
                } else {
                    $score = $price = $config[$contain[$this->params['types']] . '_price'];
                }
            /*} else {
                $recharge_user = $this->member;
                $another_user = $toUser;
            }*/
        } else {
            $recharge_user = $this->member;
            $another_user = $toUser;

            
            $configPersonal = Db::name('config_personal')->where(['user_id' => $another_user['id']])->find();
            if ($configPersonal) {
                $score = $price = $configPersonal[$contain[$this->params['types']] . '_price'];
                // if ($this->params['types'] == 1) {
                //     if ($score > 15) {
                //         $score = $price = 15;
                //     }
                // } else {
                //     if ($score > 30) {
                //         $score = $price = 30;
                //     }
                // }

                if ($config[$contain[$this->params['types']] . '_price_switch'] > 0) {
                    $score = $price = $config[$contain[$this->params['types']] . '_price'];
                }
            } else {
                $score = $price = $config[$contain[$this->params['types']] . '_price'];
            }
        }
        if ($price) {
            $overpayscale = 0;
            // 获取所有关联账号的总支付
            // $overpayscale = UserIntimate::Count($recharge_user['id'], $another_user['id'], true);
            if ($overpayscale) {
                $chat_scale['scale'] = $overpayscale;
            } else {
                $chat_scale = Db::name('limit_chat_price')->where($this->member['id']>$toUser['id'] ? 'user_id='.$toUser['id']. ' and another_id='. $this->member['id'] : 'user_id='.$this->member['id']. ' and another_id='. $toUser['id'])->find();
            }

            if ($chat_scale) {
                $score = $price = number_format($price * $chat_scale['scale'] / 100, 2);
            }
            $chat_discount = Db::name('act_chat_discount_user')->where(['user_id'=>$another_user['id'],'state'=>0, 'starttime'=>['<=', datetime()], 'endtime'=>['>=', datetime()]])->fetchSql(false)->find();
            if ($chat_discount) {
                $score = $price = number_format($price * $chat_discount['discount'] / 100, 2);
            }
        }

        $volley = Db::name('user')->master()->where(['id' => $recharge_user['id']])->value('volley');

        $chatConfig = false;
        if ($price + 0) {
            if ($recharge_user['sex'] == '女' && $recharge_user['is_identity_authentication'] = 2 && $recharge_user['yqr']) {
                $proxy = Db::name('user')->where(['yqm' => $recharge_user['yqr']])->value('proxy');

                if ($proxy) {

                    $field = $contain[$this->params['types']] . '_count';

                    if ($config[$field] + 0) {
                        Db::name('chat_records')->where(['types' => $this->params['types'] + 8, 'channel' => 1, 'user_id' => $recharge_user['id'], 'status' => 0])->delete();
                        $chatCount = Db::name('chat_records')->where(['types' => $this->params['types'] + 8, 'channel' => 1, 'user_id' => $recharge_user['id']])->whereTime('create_time', 'd')->count();
                        if ($chatCount <= $config[$field]) {
                            $price = 0;
                            $chatConfig = true;
                        }
                    }
                }
            }
        }
        $hasnotdec = in_array($recharge_user['id'], explode(',', $config['chat_over_dec_not']));
        // 通话额外扣除费用
        // $extra_rate = $volley >= 200 && !$hasnotdec ? 0.1 : 0;
        $extra_rate = 0;
        $extra_price = $price * $extra_rate;
        
        // $serviceOrder = Db::name('order_of_service')->where('((user_id='.$this->member['id'].' and shopowner='.$this->params['to_user'].') or (user_id='.$this->params['to_user'].' and shopowner='.$this->member['id'].')) and status in (0, 1) and state = 0 and paystate=1 and type=1')->count();

        // 服务订单下生成的免费聊天权限
        $timenow = time();
        $userid = $this->member['id'];
        $touserid = $this->params['to_user'];
        $chat_free = 0;
        $end_time = 0;
        $privatechat_free = Db::name('privatechat_free')->where(($userid>$touserid?"user_id=$touserid and another_id=$userid":"user_id=$userid and another_id=$touserid") . " and (end_time=0 or start_time=0 or end_time>$timenow)")->order('id asc')->find();
        if ($privatechat_free && ($this->params['types'] + 1 == $privatechat_free['method'] || $privatechat_free['method'] == 4)) {
            if ($privatechat_free['start_time'] == 0) {
            // 说明是线上订单，服务方未发起聊天
                if ($privatechat_free['server'] == $userid) {
                    $end_time = $timenow + $privatechat_free['end_time'] - $privatechat_free['create_time'];
                    $end_time = 9999999999;
                    Db::name('privatechat_free')->where(['id'=>$privatechat_free['id']])->update(['start_time'=>$timenow, 'end_time'=>$end_time]);
                    $chat_free = 1;
                }
            } else {
                $chat_free = 1;
                $end_time = $privatechat_free['end_time'] ? $privatechat_free['end_time'] : 9999999999;
            }
        } else {
            if ($price <= 0) return $this->miss($recharge_user['id'] != $this->member['id'] ? '未设置' . $msg[$this->params['types']] . '费用,不能发起'.$msg[$this->params['types']].',立即去设置收费' : '对方未设置'.$msg[$this->params['types']] . '费用,可通知对方设置', $recharge_user['id'] != $this->member['id']?201:400);
        }

        if ($chat_free || $volley >= ($price + $extra_price) || ($volley < ($price + $extra_price) && $recharge_user['free_' . $contain[$this->params['types']]])) {

            // 新增连麦限制
            $todaylimit = Db::name('privatechat_lianmai_records')->master(true)->where(['user_id'=>$this->member['id'], 'type'=>$this->params['types']])->whereTime('create_time', 'today')->order('num desc')->value('num');
            if($todaylimit >= 100){
                return $this->miss('今日已被禁止' . $msg[$this->params['types']]);
            }
            $todaylimit = Db::name('privatechat_lianmai_records')->master(true)->where(['user_id'=>$toUser['id'], 'type'=>$this->params['types']])->whereTime('create_time', 'today')->order('num desc')->value('num');
            if($todaylimit >= 100){
                return $this->miss('对方今日已被禁止' . $msg[$this->params['types']]);
            }



            if ($recharge_user['sex'] == '女') {
                $score = $price;
            }
            $order_data = ['duration' => 0, 'types' => $this->params['types'], 'price' => $price, 'money' => $price, 'score' => $score, 'another_id' => $another_user['id']];
            if(getenv('AUTO_INC')){
                $order_data['autoinc'] = getenv('AUTO_INC');
            }
            $order_data['checksocket'] = $this->params['auto'];
            $order_data['ip'] = (new Whip())->getValidIpAddress();
            $orderData = [
                'number' => uniqid(),
                'types' => 2,
                'user_id' => $recharge_user['id'],
                'money' => $recharge_user['free_' . $contain[$this->params['types']]] ? 0 : $price,
                'status' => 0,
                'create_time' => time(),
                'update_time' => time()
            ];
            if ($chat_free) {
                $orderData['money'] = 0;
                $order_data['free_time'] = $end_time;
                $order_data['free_id'] = $privatechat_free['id'];
                $order_data['free_method'] = $privatechat_free['method'];
            }

            // 是否私密通话
            $order_data['privacy'] = $toUser['id'] != $touser_id_privacy ? 1: 0;

            $orderData['data'] = json_encode($order_data);
            $orderid = Db::name('order_common')->insertGetId($orderData);


            // $has = Cache::store('redis')->get('lianmaiuser:'.$toUser['id']);
            // if ($has) {
            //     return $this->miss('忙线中,请稍后再试');
            // }
            $single = 0;
            if ($this->params['types'] == 2) {
                $chatSingle = Db::name('privatechat_lianmai_limit')->master()->where(['user_id'=>$this->member['id'], 'banned_time'=>['GT', time()]])->find();
                if ($chatSingle){
                    return $this->miss($chatSingle['reason']);
                } else {
                    $chatSingle = Db::name('privatechat_lianmai_limit_single')
                                    ->master()
                                    ->where("(user_id=".$this->member['id']." and touser_id=".$toUser['id'].") or (user_id=".$toUser['id']." and touser_id=".$this->member['id'].")")
                                    ->where(['banned_time'=>['GT', time()]])
                                    ->find();
                }
                if ($chatSingle){
                    $single = 2;
                } else {
                    $chatSingle = Db::name('privatechat_lianmai_limit')->master()->where(['user_id'=>$toUser['id'], 'banned_time'=>['GT', time()]])->find();
                    if ($chatSingle){
                        $single = 2;
                    }
                }
            }
            // if (!$user) {
                $chat_data_o = ['orderid' => (string)$orderid, 'trtc_appid'=>getenv('TLS_APPID'), 'u_d_id'=>$userInfo_privacy['device_id'], 'payer'=>$recharge_user['id']==$this->member['id']?$user_id_privacy:$touser_id_privacy];
                $chat_data = [
                    "userid" => $user_id_privacy,
                    "touserid" => $touser_id_privacy,
                    "type" => $this->params['types'] + 8,
                    'second' => 0,
                    //'isRead' => 1,
                    'isCount' => 0,
                    'single' => $single,
                    'finish' => 1,
                    "content" => '[' . $msg[$this->params['types']] . ']',
                    'order_id' => $orderid
                ];
                $chat_data['data'] = json_encode($chat_data_o, JSON_UNESCAPED_UNICODE);
                $msgid = Db::name('privatechat')->insertGetId($chat_data);


                $chat_data['id'] = $msgid;
                $TencentIMResponse = (new \app\service\TencentIM)->sendmsg($chat_data['userid'], $chat_data['touserid'], $chat_data['content']??'', $chat_data, $chat_data['single']??0);
                $chat_data_o['MsgKey'] = $TencentIMResponse['MsgKey']??'';
                $chat_data['data'] = json_encode($chat_data_o, JSON_UNESCAPED_UNICODE);
                Db::name('privatechat')->where(['id'=>$msgid])->update($chat_data);
        
                // 更新会话列表
                ChatLists::updateLists($user_id_privacy, $touser_id_privacy, $single, $this->params['types'] + 8);
            // }
            if ($chatConfig) {
                Db::name('chat_records')->insert([
                    'types' => $this->params['types'] + 8,
                    'user_id' => $recharge_user['id'],
                    'to_user' => $another_user['id'],
                    'data' => json_encode(['orderid' => $orderid]),
                    'status' => 0
                ]);
            }


            return $this->pass(['orderid' => $orderid]);
        } else {
            if ($recharge_user['id'] == $this->member['id']) {
                return $this->return['user.error.insufficientBalance'];
            } else {
                return $this->miss('对方余额不足');
            }
        }
    }
    private function checkVersion($uid, $touid)
    {
        $userRepeatChecks = Db::name('user_repeat_check')->where(['user_id'=>['in', [$uid, $touid]]])->column('*', 'user_id');
        if (sizeof($userRepeatChecks) == 2) {
            if ($userRepeatChecks[$uid]['sys_channel'] != $userRepeatChecks[$touid]['sys_channel']) {
                $config = Config::index('lianmai');
                if ($config['callto_relang_min_version'] > $userRepeatChecks[$uid]['last_login_app_version']) {
                    return '你的版本较低，通话发起失败';
                }
            }
        }
        return '';
    }

    // 连麦接通使用一次权限
    public function useOrder()
    {
        $user_id = input('user_id/d');

        $result = Db::name('order_common')->where(['user_id' => $user_id, 'types' => 2, 'status' => 1])->order('id desc')->find();
        if ($result) {
            Db::name('order_common')->where(['id' => $result['id']])->setField('status', -1);
            exit(json_encode(['code' => 200, 'msg' => '使用成功']));
        } else {
            exit(json_encode(['code' => 400, 'msg' => '数据不存在']));
        }
    }

    // 获取配置信息
    public function configbak()
    {
        $where = ['category' => ['in', ['push', 'chat', 'version', 'live', 'system', 'invite', 'pay']]];
        $whereOr = ['title' => ['in', ['family_switch', 'cluster_switch']]];

        $data = Db::name('config_system')
            ->where($where)
            ->whereOR(function ($query) use($whereOr) {
                $query->where($whereOr);
            })->column('title, content');

        $data['request_scheme'] = $_SERVER['REQUEST_SCHEME'] . '://';
        $data['rtc_appid'] = getenv('TLS_APPID');
        $data['lianmai'] = getenv('MIC_APPID');
        $data['oss_switch'] = getenv('APP_OSS');
        $data['Bucket'] = getenv('OSS_BUCKET');
        $data['Endpoint'] = getenv('OSS_ENDPOINT');
        $data['shanyan_appid_android'] = getenv('SHANYAN_APPID_ANDROID');
        $data['shanyan_appkey_android'] = getenv('SHANYAN_APPKEY_ANDROID');
        $data['shanyan_appid_ios'] = getenv('SHANYAN_APPID_IOS');
        $data['shanyan_appkey_ios'] = getenv('SHANYAN_APPKEY_IOS');
        $data['socket_prefix'] = getenv('SOCKET_PREFIX');
        $data['socket_url'] = getenv('SOCKET_PROTOCOL') . '://' . getenv('APP_URL') . getenv('SOCKET_DIR') . ':' . getenv('SOCKET_PORT');

        return $this->pass($data);
    }
    // 获取配置信息
    public function config()
    {
        if($data = cache('memberconfig')){
        }else{
            $where = ['category' => ['in', ['push', 'chat', 'version', 'live', 'system', 'invite', 'pay', 'count_steps', 'hunjie','msg_box','withdraw']]];
            $whereOr = ['title' => ['in', ['family_switch', 'cluster_switch', 'show_volley_switch', 'flag_min_day', 'address_hot', 'check_edit_nickname', 'check_edit_slogan', 'check_edit_self_slogan', 'user_list_hide', 'rank_experience_show','msg_show']]];

            $data = Db::name('config_system')
                ->where($where)
                ->whereOR(function ($query) use($whereOr) {
                    $query->where($whereOr);
                })->column('title, content');

            $data['request_scheme'] = $_SERVER['REQUEST_SCHEME'] . '://';
            $data['rtc_appid'] = getenv('TLS_APPID');
            $data['lianmai'] = getenv('MIC_APPID');
            $data['oss_switch'] = getenv('APP_OSS');
            $data['Bucket'] = getenv('OSS_BUCKET');
            $data['Endpoint'] = getenv('OSS_ENDPOINT');
            $data['shanyan_appid_android'] = getenv('SHANYAN_APPID_ANDROID');
            $data['shanyan_appkey_android'] = getenv('SHANYAN_APPKEY_ANDROID');
            $data['shanyan_appid_ios'] = getenv('SHANYAN_APPID_IOS');
            $data['shanyan_appkey_ios'] = getenv('SHANYAN_APPKEY_IOS');
            $data['socket_prefix'] = getenv('SOCKET_PREFIX');
            $data['socket_url'] = getenv('SOCKET_PROTOCOL') . '://' . getenv('APP_HOST') . getenv('SOCKET_DIR') . ':' . getenv('SOCKET_PORT');
            cache('memberconfig', $data, 60);
        }

        $d = IpInfoUtils::infoold((new Whip())->getValidIpAddress());
        // $data['pgshangjia2'] = 0;
        // $data['pgshangjia'] = 0;
        // $data['ios_shang_force'] = 0;
        // $data['pgshangjia2'] = $d['country'] && $d['country'] != '中国' ? 1 : $data['pgshangjia2'];
        // $data['pgshangjia'] = $d['country'] && $d['country'] != '中国' ? 1 : $data['pgshangjia'];
        // $data['ios_shang_force'] = $d['country'] && $d['country'] != '中国' ? 1 : 0;

        if (is_array($d['city']) || in_array($d['city'], ['宁德市','宁德','福州市','福州','泉州市','泉州','XX',''])) {
            $data['Bucket'] = 'oss-zaima';
            $data['Endpoint'] = 'nihaozaima.com';
        }
        $data['ipinfo'] = $d;
        $data['overseas'] = 0;
        $data['hide_audio_to_text'] = 1;
        // $data['overseas'] = $d && $d['country'] != '中国' ? 1 : 0;

        $data['web_enter'] = 'http://'.getenv('APP_URL').'/index.html';
        $data['relang_web_enter'] = 'http://'.getenv('APP_URL_2').'/index.html';

        
        $data['app_rate'] = (int)getenv('APP_RATE');
        return $this->pass($data);
    }

    // 隐私设置
    public function secrecy()
    {
        $user_id = input('user_id/d');

        $field = input('field');  // hide_search 对他人隐身 | hide_distance 隐藏距离 | hide_online_time 隐藏在线时间

        $current_field = Db::name('user')->where(['id' => $user_id])->value($field);

        if ($current_field) {
            Db::name('user')->where(['id' => $user_id])->setField($field, 0);
            $msg = '已关闭';
        } else {
            Db::name('user')->where(['id' => $user_id])->setField($field, 1);
            $msg = '已开启';
        }

        return json(['code' => 200, 'msg' => $msg]);
    }

    // 设置手势密码
    public function shoushi()
    {
        $user_id = input('user_id/d');
        $password = input('password');

        Db::name('user')->where(['id' => $user_id])->setField('shoushi', $password);

        return json(['code' => 200, 'msg' => '设置成功']);
    }

    // 注销账号
    public function deleteAccountbak()
    {
        /*$result = Code::verifyCode($this->member['phone'], $this->params['code']);
        if ($result['code'] == 400) {
            return $this->miss($result['msg']);
        }*/

        $contain = [
            'channel' => 1,
            'user_id' => $this->member['id'],
            'phone' => $this->member['phone'],
            'data' => json_encode($this->member),
            'ip' => (new Whip())->getValidIpAddress(),
            'os' => $_SERVER['HTTP_USER_AGENT'] ?? '',
            'create_time' => time(),
        ];

        Db::name('recycle_user')->insert($contain);

        User::update([
            'id' => $this->member['id'],
            'name' => '已注销',
            'phone' => null,
            'qq_openID' => null,
            'wechat' => null,
            'device_id' => null,
            'delete_time' => time()
        ]);

        //User::destroy($this->member['id']);

        return json(['code' => 200, 'msg' => '账号已注销']);
    }
    // 注销账号
    public function deleteAccount()
    {
        if(input('code')){
            $result = Code::verifyCode($this->member['phone'], input('code'));
            if ($result['code'] == 400) {
                return $this->miss($result['msg']);
            }
        } else if(input('ecode')){
            $email = Db::name('user_auth')->where(['user_id'=>$this->member['id'], 'type'=>1, 'state'=>1])->value('account');
            $result = Code::verifyEmailCode($email, input('ecode'));
            if ($result['code'] == 400) {
                return $this->miss($result['msg']);
            }
        } else {
            return $this->miss('操作异常');
        }
  
        if ($this->member['sex'] == '男') {
            $ip = (new Whip())->getValidIpAddress();
            $os= $_SERVER['HTTP_USER_AGENT'] ?? '';
            $now_time = time();
             Db::name('recycle_review')->where(['user_id'=>$this->member['id']])->delete();
             $contain = [
                 'user_id' => $this->member['id'],
                 'ip' => $ip,
                 'os' => $os,
                 'create_time' => $now_time,
                 'update_time' =>$now_time,
                 'state' => 1,
                 'remark' => '用户通过APP主动注销账号',
                 'admin_id' => 0,
             ];
             Db::name('recycle_review')->insert($contain);
             Db::name('recycle_user')->insert([
                 'channel' => 1,
                 'user_id' =>$this->member['id'],
                 'phone' => $this->member['phone']??'',
                 'data' => json_encode($this->member),
                 'ip' => $ip,
                 'os' => $os,
                 'create_time' =>$now_time,
             ]);
             $logout_update = [
                //  'name' => '已注销',
                //  'phone'=>null,
                 'wechat'=>null,
                 'qq_openID'=>null,
                 'delete_time' => $now_time
             ];
             Db::name('user')->where(['id'=>$this->member['id']])->update($logout_update);
             Db::name('chat_lists')->where(['user_id'=>$this->member['id']])->update(['another_unread'=>0]);
             Db::name('chat_lists')->where(['another_id'=>$this->member['id']])->update(['user_unread'=>0]);
             return $this->pass('注销成功');
         }
  
        $has = Db::name('recycle_review')->where(['user_id'=>$this->member['id'], 'state'=>0])->find();
        if(!$has){
            $contain = [
                'user_id' => $this->member['id'],
                'ip' => (new Whip())->getValidIpAddress(),
                'os' => $_SERVER['HTTP_USER_AGENT'] ?? '',
                'create_time' => time(),
            ];
            Db::name('recycle_review')->insert($contain);
            UserWarn::CheckWarn($this->member['id'], '发起注销申请');
        }
        return $this->pass('账号注销申请已提交，若平台审核前再次登录表示取消本次注销');
    }

    // 重置推送开关设置
    public function resetPush()
    {
        $user_id = input('user_id');

        try {
            Db::name('push_member')->where(['user_id' => $user_id])->delete();

            /*Db::name('push_member')->insertAll([
                ['cid' => 1, 'user_id' => $user_id],
                ['cid' => 2, 'user_id' => $user_id],
            ]);*/

            $ids = Db::name('push_category')->where(['is_hidden' => 0])->column('id');
            if ($ids) {
                $contain = [];
                foreach ($ids as $k => $v) {
                    $contain[] = ['cid' => $v, 'user_id' => $user_id];
                }
                Db::name('push_member')->insertAll($contain);
            }

        } catch (\Exception $e) {
            return json(['code' => 400, 'msg' => $e->getMessage()]);
        }

        return json(['code' => 200, 'msg' => 'success']);
    }

    // 从事职业
    public function occupation()
    {
        $data = Db::name('user_occupation')->field('id, name')->where(['hide' => 0])->order('des desc, id asc')->select();

        exit(json_encode(['code' => 200, 'data' => $data]));
    }

    // 约会节目
    public function conditions()
    {
        $type = input('type/d') ? input('type/d') : 1;

        $data = Db::name('user_conditions')->field('id, name')->where(['type' => $type, 'hide' => 0])->order('des desc, id asc')->select();

        exit(json_encode(['code' => 200, 'data' => $data]));
    }

    // 消费记录
    public function records()
    {
        $page = input('page/d');
        $user_id = input('user_id/d');

        $data = Db::name('volley_desc')
            ->field('content, price, FROM_UNIXTIME(time,"%Y-%m-%d %H:%i") time')
            ->where(['user_id' => $user_id, 'types' => 0])
            ->order('id desc')
            ->page($page)->select();

        exit(json_encode(['code' => 200, 'data' => $data]));
    }

    // 删除动态
    public function delDymanic()
    {
        $id = input('id/d');

        $dyinfo = Db::name('dymanic')->where(['dy_id'=>$id])->find();
        if ($dyinfo['userid'] != $this->member['id']) {
            $userid_privacy = Db::name('user')->where(['reg'=>2,'authcode'=>$this->member['id']])->value('id');
            if (!($userid_privacy && $userid_privacy == $dyinfo['userid'])) {
                return $this->miss('异常操作');
            }
        }
        $result = Db::name('dymanic')->where(['dy_id'=>$id])->delete();
        if ($result) {
            Db::name('dycomment')->where(['dy_id' => $id])->delete();
            Db::name('dymanic_collection_term')->where(['dy_id' => $id])->delete();

            exit(json_encode(['code' => 200, 'msg' => '删除成功']));
        } else {
            exit(json_encode(['code' => 400, 'msg' => '删除失败']));
        }
    }

    // 删除动态评论
    public function delComment()
    {
        $id = input('id/d');
        $user_id = input('user_id/d');

        if (!$id || !$user_id) {
            return json(['code' => 400, 'msg' => '参数有误']);
        }

        $dycomment = Db::name('dycomment')->where(['comment_id' => $id])->find();

        if ($dycomment['userid'] != $user_id) {
            $author = Db::name('dymanic')->where(['dy_id' => $dycomment['dy_id']])->value('userid');

            if ($author != $user_id) {
                return json(['code' => 400, 'msg' => '无权限删除']);
            }
        }
        Db::name('dycomment')->delete($id);

        $comments = Db::name('dymanic')->where(['dy_id' => $dycomment['dy_id']])->value('comments');

        if ($comments) {
            Db::name('dymanic')->where(['dy_id' => $dycomment['dy_id']])->setDec('comments');
        }

        exit(json_encode(['code' => 200, 'msg' => '删除成功']));
    }

    // 领取vip天数
    public function receive(Request $request = null)
    {
        $user = User::get($request->param('id'));

        if (!$user) return json(['code' => 400, 'msg' => '用户不存在']);
        if (!$user['vip_num']) return json(['code' => 400, 'msg' => '暂无可领取的会员天数']);

        $vip_end_datetime = strtotime($user['vip_end_datetime']);

        if ($vip_end_datetime < time()) {
            $time = date('Y-m-d H:i:s', strtotime($user['vip_num'] . ' day'));
        } else {
            $time = date('Y-m-d H:i:s', strtotime($user['vip_num'] . ' day', $vip_end_datetime));
        }

        User::update([
            'id' => $user['id'],
            'vip_num' => 0,
            'vip_end_datetime' => $time
        ]);

        return json(['code' => 200, 'msg' => '领取成功']);
    }

    // 团队
    public function team(): Json
    {
        $type = $this->params['type'] ?? 1;
        $level = min($this->params['level'] ?? 1, 3); // 限制最大层级为 3
        $page = $this->params['page'] ?? 1;
        $user_id = $this->params['id'] ?? 0;
        $keyword = $this->params['keyword'] ?? '';
        $start_day = strtotime($this->params['date'] ?? '') ?: strtotime("-1 day");
        $end_day = $start_day + 86400;
    
        $user = User::field('yqm')->where(['id' => $user_id])->find();
        if (!$user) {
            return $this->pass('用户不存在', 'msg');
        }
    
        // 构造最多 3 层的完整团队 yqm 列表
        $teamYqmAll = [$user['yqm']];
        $tmp = [$user['yqm']];
        for ($i = 0; $i < 3; $i++) {
            $yqms = Db::name('user')->where(['yqr' => ['in', $tmp]])->column('yqm');
            if (!$yqms) break;
            $teamYqmAll = array_merge($teamYqmAll, $yqms);
            $tmp = $yqms;
        }
    

        // === 新增：两种类型的总数量统计 ===
        $team_total = Db::name('user')->where(['id' => ['neq', $user_id],'yqr' => ['in', $teamYqmAll]])->count();
        $person_total = Db::name('user')->where(['yqr' => $user['yqm']])->count();
        
        // === 当前查询条件 ===
        if ($type == 1) {
            $where = ['id' => ['neq', $user_id], 'yqm' => ['in', $teamYqmAll]];
        } else {
            $where = ['u.yqr' => $user['yqm']];
        }
    
        if ($keyword) {
            $where['id|name'] = ['like', "%$keyword%"];
        }
        
    
        $cacheKey = "team_list_{$user_id}_{$type}_{$level}_{$page}_" . md5($keyword);
         $data = cache($cacheKey);
     
    
        if (!$data) {
             // sj 子查询
            // $sj_sql = Db::name('yaoqing_records')
            //     ->field('uid, SUM(money) AS sum_money')
            //     ->where('type', 1)
            //     ->where('data', 0)
            //     ->where('content', 'NOT LIKE', '%充值%')
            //     ->where('time', '>=', $start_day)
            //     ->where('time', '<', $end_day)
            //     ->group('uid')
            //     ->buildSql();

            // // cz 子查询
            // $cz_sql = Db::name('yaoqing_records')
            //     ->field('uid, SUM(money) AS sum_money')
            //     ->where('type', 1)
            //     ->where('data', 0)
            //     ->where('content', 'LIKE', '%充值%')
            //     ->where('time', '>=', $start_day)
            //     ->where('time', '<', $end_day)
            //     ->group('uid')
            //     ->buildSql();
            
            // $data = Db::name('user')->alias('u')
            //     ->field([
            //         'u.id',
            //         'u.name',
            //         'u.head_100 AS avatar',
            //         'u.register_datetime',
            //         'u.sex',
            //         'u.level',
            //         'u.yqm',
            //         'IFNULL(sj.sum_money, 0) AS sj_shouyi',
            //         'IFNULL(cz.sum_money, 0) AS cz_shouyi',
            //         'IFNULL(dc.direct_count, 0) AS direct_user_num',
            //         'IFNULL(ir.state, 0) AS state'
            //     ])
            //     // ->join('(SELECT uid, SUM(money) AS sum_money FROM yaoqing_records WHERE type=1 AND data=0 AND content NOT LIKE "%充值%" GROUP BY uid) sj', 'sj.uid = u.id', 'LEFT')
            //     // ->join('(SELECT uid, SUM(money) AS sum_money FROM yaoqing_records WHERE type=1 AND data=0 AND content LIKE "%充值%" GROUP BY uid) cz', 'cz.uid = u.id', 'LEFT')
            //     ->join([$sj_sql => 'sj'], 'sj.uid = u.id', 'LEFT')
            //     ->join([$cz_sql => 'cz'], 'cz.uid = u.id', 'LEFT')
            //     ->join('(SELECT yqr, COUNT(*) AS direct_count FROM user GROUP BY yqr) dc', 'dc.yqr = u.yqm', 'LEFT')
            //     ->join('(SELECT t1.touserid, t1.state FROM user_invite_record t1 INNER JOIN (SELECT touserid, MAX(id) AS max_id FROM user_invite_record GROUP BY touserid) t2 ON t1.touserid=t2.touserid AND t1.id=t2.max_id) ir', 'ir.touserid = u.id', 'LEFT')
            //     ->where($where)
            //     ->order('u.id desc')
            //     ->page($page, 10)
            //     ->select();
                
                
                
                
             $data = Db::name('user')->alias('u')
                ->field([
                    'u.id',
                    'u.name',
                    'u.head_100 AS avatar',
                    'u.register_datetime',
                    'u.sex',
                    'u.level',
                    'u.yqm',
                    'IFNULL(dc.direct_count, 0) AS direct_user_num',
                    'IFNULL(ir.state, 0) AS state',
                    'u.delete_time',
                    "IF(u.delete_time = 0 OR u.delete_time IS NULL, '', FROM_UNIXTIME(u.delete_time, '%Y-%m-%d')) AS delete_time_1"
                ])
                ->join('(SELECT yqr, COUNT(*) AS direct_count FROM user GROUP BY yqr) dc', 'dc.yqr = u.yqm', 'LEFT')
                ->join('(SELECT t1.touserid, t1.state FROM user_invite_record t1 INNER JOIN (SELECT touserid, MAX(id) AS max_id FROM user_invite_record GROUP BY touserid) t2 ON t1.touserid=t2.touserid AND t1.id=t2.max_id) ir', 'ir.touserid = u.id', 'LEFT')
                ->where($where)
                ->order('u.id desc')
                ->page($page, 10)
                ->select();
            //当日起止时间
            $todayStart = date('Y-m-d 00:00:00',$start_day);
            $todayEnd = date('Y-m-d 23:59:59',$end_day);
            
            foreach ($data as  $key=>&$val){
                $total_income = Db::name('yaoqing_records')
                    ->where('time','between',[$start_day,$end_day])
                    ->where('type', 1)
                    ->where('data', 0)
                    ->where('uid', $val['id'])
                    ->sum('money');
                $cz_sql3 = Db::name('yaoqing_records')
                    ->where('time','between',[$start_day,$end_day])
                    ->where('type', 1)
                    ->where('data', 0)
                    ->where('uid', $val['id'])
                    ->where('content', 'LIKE', '%充值%')
                    ->sum('money');
                // $val['cz_shouyi'] = $cz_sql3;
                // $val['sj_shouyi'] = $total_income-$cz_sql3 ;
                // 强制保留两位小数
                $val['cz_shouyi'] = number_format((float)$cz_sql3, 2, '.', '');
                $val['sj_shouyi'] = number_format((float)($total_income - $cz_sql3), 2, '.', '');
                
                //此处计算当日充值金额

                // 计算金币充值
                $chongzhi = Db::name('topup')
                    ->where('fk_userid', $val['id'])
                    ->where('state', 1)
                    ->where('addtime', '>=', $todayStart)
                    ->where('addtime', '<=', $todayEnd)
                    ->sum('price');//人民币


                // 计算会员充值
                $huiyuan = Db::name('order_common')
                    ->where('types', 6)
                    ->where('user_id', $val['id'])
                    ->where('status', 1)
                    ->where('update_time', '>=', strtotime($todayStart))
                    ->where('update_time', '<=', strtotime($todayEnd))
                    ->sum('money');//人民币

                $val['topupMoney'] = $chongzhi + $huiyuan;
                $val['topupMoney'] = number_format($val['topupMoney'], 2, '.', '');
            }
            
 
    
            // $sql1= Db::getLastSql();
            // $date = date('Y-m-d H:i:s');
            // file_put_contents("./log.txt", "[$date] " . $sql1 . PHP_EOL, FILE_APPEND);
    
            foreach ($data as &$item) {
                // $item['state_text'] = $item['state'] == 1 ? '有效' : '失效';
                $item['state_text'] = $item['state'] == 1 ? '' : '';
                $item['avatar'] = changeUrl($item['avatar']);
                $item['register_datetime'] = date('Y-m-d', strtotime($item['register_datetime']));
            }
    
            cache($cacheKey, $data, 5); // 缓存60秒
        }
    
        // 当前用户自身收益（不缓存）
        $sjincome = Db::name('yaoqing_records')->where([
            'uid' => $user_id,
            'type' => 1,
            'data' => 0,
            'content' => ['not like', '%充值%'],
            'time' => ['between', [$start_day, $end_day]]
        ])->sum('money');
    
        $czincome = Db::name('yaoqing_records')->where([
            'uid' => $user_id,
            'type' => 1,
            'data' => 0,
            'content' => ['like', '%充值%'],
            'time' => ['between', [$start_day, $end_day]]
        ])->sum('money');
        
        // 强制保留两位小数（解决浮点数精度问题）
        $sjincome = number_format((float)$sjincome, 2, '.', '');
        $czincome = number_format((float)$czincome, 2, '.', '');
    
        return $this->pass($data, 'data', [
            'team_total' => $team_total, // 限层级团队总数
            'person_total' => $person_total, // 全团队总数
            'sjincome' => round($sjincome, 2),
            'czincome' => round($czincome, 2),  
        ]);
           
    }

    public function teamDetail()
    {
        $data['income_today'] = Db::name('yaoqing_records')
            ->field('id, uid, money,content,FROM_UNIXTIME(time,"%Y-%m-%d %H:%i") time')
            ->where(['uid' => $this->member['id'], 'type' => 1, 'data' => 0, 'touid'=>['>',0]])
            ->where('content not like "向%" and content <> "邀请奖励" and content not like "回复%" and content not like "接听%" and content not like "收获%" and content not like "经验文章%" and content <> "服务订单完成结算" and content not like "%绑定提成补发"')
            ->whereTime('time', 'today')
            ->sum('money');
        $data['income_all'] = 0;

        $data['next_count'] = Db::name('user')->where(['yqr'=>$this->member['yqm'], 'reg'=>1, 'delete_time'=>0])->count();
        $last_months = Db::name('user')->where(['yqr'=>$this->member['yqm'], 'reg'=>1, 'delete_time'=>0])->whereTime('register_datetime','last month')->select();
        $data['last_month_count'] = sizeof($last_months);
        $data['last_month_act_count'] = 0;
        if ($data['last_month_count']) {
            $data['last_month_act_count'] = Db::name('user_data')->where(['user_id'=>['in', array_column($last_months, 'id')]])->where('income_last_month>0 or topup_last_month')->count();
        }

        return $this->pass($data);
    }
    public function teamIncomeLists(Request $request = null)
    {
        $page = $request->param('page') ?: 1;
        $pagesize = $request->param('pagesize') ?: 10;
        $types = $request->param('types') ?: 0;
        $cate = $request->param('cate') ?: 0;

        $source_type = $request->param('source_type') ?: 0;
        $search_uid = $request->param('search_uid') ?: 0;
        $date = $request->param('date') ?: '';

        $whereTypes = ['收获礼物','视频','语音','聊天','其他'];

        $where = ['uid' => $this->member['id'], 'type' => 1, 'data' => $types, 'touid'=>['>',0]];

        if ($source_type) {
            $uids = db('user')->where(['yqr'=>$this->member['yqm']])->column('id');
            if ($source_type == 1) {
                $where['source_uid'] = ['in', $uids];
            } else if ($source_type == 2) {
                $where['source_uid'] = ['not in', $uids];
            }
        }
        if ($search_uid) {
            $where['source_uid'] = $search_uid;
        }
        if ($date) {
            $where['time'] = ['between', [strtotime($date), strtotime($date) + 86399]];
        }

        $shejiao = 0;
        $chongzhi = 0;

        if($cate){
            if($cate < 5){
                $data = Db::name('yaoqing_records')
                    ->field('id, content, money, time, data types, order_id, show_money')
                    ->where($where)
                    ->where('content like "%'.$whereTypes[$cate - 1].'%" and content not like "向%" and content <> "邀请奖励" and content not like "回复%" and content not like "接听%" and content not like "收获%" and content not like "经验文章%" and content <> "服务订单完成结算" and content not like "%绑定提成补发"')
                    ->order('id desc')->page($page, $pagesize)->select();
            }else{
                $wherenotlike = [];
                for ($i=0; $i < 4; $i++) { 
                    $wherenotlike[] = 'content not like "%'.$whereTypes[$i].'%"';
                }
                $wherenotlike[] = 'content not like "向%" and content <> "邀请奖励" and content not like "回复%" and content not like "接听%" and content not like "收获%" and content not like "经验文章%" and content <> "服务订单完成结算" and content not like "%绑定提成补发"';
                $data = Db::name('yaoqing_records')
                    ->field('id, content, money, time, data types, order_id, show_money')
                    ->where($where)
                    ->where(implode(' and ', $wherenotlike))
                    ->order('id desc')->page($page, $pagesize)->select();
            }
        }else{
            $data = Db::name('yaoqing_records')
                ->field('id, content, money, time, data types, order_id, show_money')
                ->where($where)
                ->where('content not like "向%" and content <> "邀请奖励" and content not like "回复%" and content not like "接听%" and content not like "收获%" and content not like "经验文章%" and content <> "服务订单完成结算" and content not like "%绑定提成补发"')
                ->order('id desc')->page($page, $pagesize)->select();
            $shejiao = Db::name('yaoqing_records')
                ->field('id, content, money, time, data types, order_id, show_money')
                ->where($where)
                ->where('content not like "向%" and content <> "邀请奖励" and content not like "回复%" and content not like "接听%" and content not like "收获%" and content not like "经验文章%" and content <> "服务订单完成结算" and content not like "%绑定提成补发" and content like "%) 聊天 %"')
                ->sum('money');
            $chongzhi = Db::name('yaoqing_records')
                ->field('id, content, money, time, data types, order_id, show_money')
                ->where($where)
                ->where('content not like "向%" and content <> "邀请奖励" and content not like "回复%" and content not like "接听%" and content not like "收获%" and content not like "经验文章%" and content <> "服务订单完成结算" and content not like "%绑定提成补发" and content like "%) 充值 %"')
                ->sum('money');
        }


        foreach ($data as $key => $item) {
            $data[$key]['time'] = date('m-d H:i:s', $item['time']);
            $data[$key]['money'] = $item['show_money'] != 0 ? $item['show_money'] : $item['money'];

            unset($data[$key]['order_id']);
            unset($data[$key]['show_money']);
        }

        return $this->pass($data, 'data', compact('shejiao', 'chongzhi'));
    }

    // 代理商推广红包收益
    public function income()
    {
        $user_id = input('user_id');

        $data = Db::name('yaoqing_records')
            ->field('id, uid, money,content,FROM_UNIXTIME(time,"%Y-%m-%d %H:%i") time')
            ->where(['uid' => $user_id, 'type' => 1, 'data' => 0, 'touid'=>['>',0]])
            ->where('content not like "向%" and content <> "邀请奖励" and content not like "回复%" and content not like "接听%" and content not like "收获%" and content not like "经验文章%" and content <> "服务订单完成结算" and content not like "%绑定提成补发"')
            ->order('id desc')->paginate(100)->toArray();

        return json(['code' => 200, 'data' => $data]);
    }

    public function rewardRanking()
    {
        $page = input('page/d') ?: 1;

        $data = Db::name('user')
            ->field('id, name, head_100 avatar, shouyi, shouyi_xuni')
            ->order('shouyi_xuni desc, shouyi desc')
            ->page($page, 10)->select();

        foreach ($data as $key => $item) {
            $data[$key]['avatar'] = changeUrl($item['avatar']);

            if ($item['shouyi_xuni'] + 0) {
                $data[$key]['money'] = $item['shouyi_xuni'];
            } else {
                $data[$key]['money'] = $item['shouyi'];
            }

            $data[$key]['money'] = round($data[$key]['money'] / getenv('APP_RATE'), 2);

            unset($data[$key]['shouyi'], $data[$key]['shouyi_xuni']);
        }

        return $this->pass($data);
    }

    //-------------------------------

    // 语音视频扣费
    public function createMic()
    {
        $User = new User;

        $order = Db::name('order_common')->master()->find($this->params['orderid']);

        if (!$order) {
            return $this->return['common.error.notExist'];
        }

        $time = time();

        $data = json_decode($order['data'], true);

        // 做通话结束判断，避免扣费方因网路问题未退出通话界面持续扣费
        if(isset($data['end'])){
            return $this->miss('通话已结束1');
        }

        if(isset($data['autoinc'])){
            if(isset($data['end'])){
                return $this->miss('通话已结束2');
            }
            $start_time = $time;
            if ($data['duration']) {
                if(isset($data['start'])){
                    $start_time = $data['start'];
                    $realminute = ceil(($time - $data['start']) / 60);
                    if($realminute - $data['duration'] > 1){
                        return $this->miss('通话已结束3');
                    }
                    if($realminute > $data['duration']){
                        $data['duration'] = $realminute - 1;
                    }
                }
            }
            if($data['types'] == 2){
                ShenheTask::CreateTask($this->member['id'],$order['id']);
            }
            return json(['code' => 200, 'data' => ['orderid' => $order['id'], 'nexttime'=> $start_time + $data['duration'] * 20, 'reqfailexit'=>0]]);
        }

        /*if ($data && isset($data['duration']) && $data['duration'] == 1 && ($order['update_time'] + 30) < time()) {
            return json(['code' => 200, 'data' => ['orderid' => $order['id']]]);
        }*/

        //$chat = Db::name('privatechat')->where(['type' => ['in', [9,10]], 'data' => ['like', '{"orderid":"'.$order['id'].'"%']])->find();
        $chat = Db::name('privatechat')->master()->where(['type' => ['in', [9,10]], 'order_id' => $order['id']])->find();

        if(!$chat){
            return $this->miss('通话异常');
        }
        $chat_data = json_decode($chat['data'], true);
        if(!isset($chat_data['status']) || $chat_data['status'] != 1){
            return $this->miss('通话不存在');
        }

        $free_use = 0;  // 是否使用账户免费时间
        $status = 1;


    
        // 通话额外扣除费用
        // $extra_rate = 0.1;
        $extra_rate = 0;
    
        $toUser_privacy = $toUser = Db::name('user')->master()->find($chat['touserid']);
        $user_privacy = $this->member;
        if ($toUser['reg'] == 2) {
            $toUser = Db::name('user')->master()->find($toUser['authcode']);
            $this->member = Db::name('user')->master()->find($this->member['authcode']);
        }
    
        // 系统推送的女用户和男性聊天，将由男方付费
        if ($toUser['id'] == $order['user_id']) {
            /*$greetRecords = Db::name('greet_records')->where(['user_id' => $toUser['id'], 'to_user' => $this->member['id']])->find();
        
            if ($greetRecords) {*/
                $recharge_user = $toUser;
                $another_user = $this->member;
            /*} else {
                $recharge_user = $this->member;
                $another_user = $toUser;
            }*/
        } else {
            $recharge_user = $this->member;
            $another_user = $toUser;
        }

        if ($recharge_user['noble_time'] > $time && $recharge_user['noble_grade']) {
            $gradeNoble = GradeNoble::get(['grade' => $recharge_user['noble_grade']]);

            if ($gradeNoble) {
                $privilege = explode(',',$gradeNoble['privilege']);

                if ($data['types'] == 1) {
                    $privilege_field = 11;
                    $privilegeValue_field = 1;
                } else {
                    $privilege_field = 12;
                    $privilegeValue_field = 2;
                }

                if (in_array($privilege_field, $privilege)) {
                    $privilegeValue = explode(',',$gradeNoble['value']);

                    if (isset($privilegeValue[$privilegeValue_field]) && $privilegeValue[$privilegeValue_field]) {
                        $userCount = Db::name('grade_noble_use')->where(['types' => $privilegeValue_field + 1, 'user_id' => $recharge_user['id'], 'create_time' => ['egt', strtotime(date('Ymd'))]])->count();

                        if ($privilegeValue[$privilegeValue_field] > $userCount) {
                            Db::name('grade_noble_use')->insert(['types' => $privilegeValue_field + 1, 'user_id' => $recharge_user['id'], 'create_time' => $time]);

                            $status = 0;
                        }
                    }
                }
            }
        }

        $start_time = $time;


        // 异常状态下缺失开始时间，补充开始时间避免损失过大
        if(isset($data['start'])){
            $start_time = $data['start'];
        }else{
            $buildtime = $time - $order['create_time'] <= 60 ? $time : $order['create_time'] + 10;
            $start_time = $data['start'] = $buildtime;
        }
        if ($data['duration']) {
            $price = $add = $data['money'] / $data['duration'];
            $score = $data['score'] / $data['duration'];

            $realminute = ceil(($time - $data['start']) / 60);
            if($realminute > $data['duration']){
                $price = number_format($add = $price * ($realminute - $data['duration']), 2);
                $score = number_format($score * ($realminute - $data['duration']), 2);
                $data['duration'] = $realminute - 1;
            }
        } else {
            $price = $add = $order['money'];
            $score = $data['score'];

            // 任务
            $task = $chat['type'] == 9 ? 'voice_chat' : 'video_chat';
            Task::finish($task, $this->member['id']);
        }



        if ($status) {
            $free_time_field = $chat['type'] == 9 ? 'free_voice' : 'free_video';

            if ($recharge_user[$free_time_field] > 0) {
                Db::name('user')->where(['id' => $recharge_user['id']])->setDec($free_time_field);
                $free_use = 1;
            } else {
                $chatRecords = Db::name('chat_records')->where(['user_id' => $recharge_user['id'], 'data' => '{"orderid":"'.$order['id'].'"}'])->find();
                if ($chatRecords) {
                    $price = 0;

                    if (!$chatRecords['status']) {
                        Db::name('chat_records')->where(['id' => $chatRecords['id']])->setField('status', 1);
                    }
                } else {
                    $extra_price = $price * $extra_rate;
                    
                    if ($recharge_user['volley'] < ($price + $extra_price)) {
                        return $this->return['user.error.insufficientBalance'];
                    }
                }
            }
        }
        
        $add_money = $free_use || !$status ? 0 : $add;
        
        $add_money = $data['duration'] ? $add_money : 0;
        $data['money'] = $data['duration'] ? $data['money'] + $add : $data['money'];
        $data['score'] = $data['duration'] ? $data['score'] + $score : $data['score'];
        
        // $time_now = $time;

        // if(isset($data['start']) && $data['start'] && isset($data['duration']) && $data['duration']){
        //     $data['duration'] = ceil(($time_now - $data['start']) / 60);
        // }else{
        //     $data['duration'] = 1;
        // }

        $data['duration'] += 1;

        // 补充最后一次扣费的时间
        $data['endinc'] = $time;

        try {
            $data['ip'] = (new Whip())->getValidIpAddress();
        }catch (Exception $e) {
            
        }

        
        Db::name('order_common')->where(['id' => $order['id']])->update([
            'money' => $order['money'] + $add_money,
            'status' => 1,
            'data' => json_encode($data),
            'update_time' => $time
        ]);

        $msg = trim($chat['content'], '[]');

        $toUserInfo = $toUser_privacy;
    
        if ($recharge_user['id'] == $this->member['id']) {
            $recharge_msg = '向 ' . $toUserInfo['name'] . '(' . $chat['touserid'] . ') 发起' . $msg . '付费。分钟数:' . $data['duration'];
        } else {
            $recharge_msg = $user_privacy['name'] . '(' . $user_privacy['id'] . ') 发起' . $msg . '付费。分钟数:' . $data['duration'];
        }




        //$desc = Db::name('volley_desc')->where(['content' => $recharge_msg])->find();
        $desc = Db::name('volley_desc')->master()->where(['order_id' => $order['id']])->find();

        $volley_price = $free_use || !$status ? 0 : $add;

        $balance = $User->master()->where(['id' => $recharge_user['id']])->value('volley');
        $current_balance = $balance - $volley_price - $volley_price * $extra_rate;
        if ($desc) {
            Db::name('volley_desc')->where(['id' => $desc['id']])->update([
                'price' => $desc['price'] + $volley_price,
                'balance' => $current_balance,
                'content' => $recharge_msg,
            ]);
        } else {
            Db::name('volley_desc')->insert([
                'user_id' => $recharge_user['id'],
                'content' => $recharge_msg,
                'price' => $volley_price,
                'balance' => $current_balance,
                'order_id' => $order['id'],
                'time' => $time
            ]);
        }
        // 用户消费统计
        UserData::createData($recharge_user['id'], $volley_price, 'consume');
    
        // if ($this->member['sex'] == '男' && $toUser['sex'] == '女') {
        //     $chat_score = $data['money'] / $data['duration'];
        // } else {
            $chat_score = $volley_price;
        // }
        
        Db::name('privatechat')->where(['id' => $chat['id']])->update([
            'second' => $chat['second'] + 1,
            'money' => $chat['money'] + $volley_price,
            'score' => $chat['score'] + $chat_score
        ]);

        if (($volley_price + 0) && (!$free_use || $status)) {
            $extra_price = $volley_price * $extra_rate;
            Db::name('user')->where(['id' => $recharge_user['id']])->setDec('volley', ($volley_price + $extra_price));
        }
        
        if ($recharge_user['id'] == $this->member['id']) {
            if ($this->member['sex'] == '女' && $toUserInfo['sex'] == '男') {
                User::changeIntimate($this->member['id'], $chat['touserid'], $score, '向' . $toUserInfo['name'] . '(' . $toUserInfo['id'] . ') 发起' . $msg, $order['id'],1,1,'chat',$chat_score,1);

            } else {
                User::changeIntimate($this->member['id'], $chat['touserid'], $price, '接听 ' . $user_privacy['name'] . '(' . $user_privacy['id'] . ') 的' . $msg, $order['id'],1,1,'chat',$chat_score);
            }
        } else {
            if ($this->member['sex'] == '女' && $toUserInfo['sex'] == '男') {
                User::changeIntimate($chat['touserid'], $this->member['id'], $score, '向' . $toUserInfo['name'] . '(' . $toUserInfo['id'] . ') 发起' . $msg, $order['id'],1,1,'chat',$score);

            } else {
                User::changeIntimate($chat['touserid'], $this->member['id'], $price, '向' . $toUserInfo['name'] . '(' . $toUserInfo['id'] . ') 发起' . $msg, $order['id'],1,1,'chat',$chat_score);
            }
            
        }
        if($data['duration'] == 1 && $msg == '视频通话'){
            ShenheTask::CreateTask($this->member['id'],$order['id']);
        }

        $nexttime = $start_time + $data['duration'] * 60;
        if($nexttime <= $time){
            $nexttime = $time + 60;
        }

        return json(['code' => 200, 'data' => ['orderid' => $order['id'], 'nexttime'=> $nexttime]]);
    }

    // 备注
    public function remark()
    {
        $name = input('name');

        if (strlen($name) > 64) return json(['code' => 400, 'msg' => '备注名过长']);

        $data = Db::name('user_remark')->where(['user_id' => $this->member['id'], 'to_user' => $this->params['to_user']])->find();
        if ($data) {
            if ($name) {
                Db::name('user_remark')->where(['id' => $data['id']])->setField('name', $name);
            } else {
                Db::name('user_remark')->delete($data['id']);
            }
        } else {
            Db::name('user_remark')->insert(['user_id' => $this->member['id'], 'to_user' => $this->params['to_user'], 'name' => $name]);
        }

        return json(['code' => 200, 'msg' => '修改成功']);
    }

    public function frozenrecords()
    {
        $user_id = input('user_id');
        $page = input('page/d', 1);
        $pagesize = input('pagesize/d', 20);
        $list = Db::name('wallet_frozen_records')->where(['user_id'=>$user_id])->order('id desc')->limit(($page - 1) * $pagesize, $pagesize)->select();
        foreach ($list as $key => $value) {
            $list[$key]['time'] = date('Y-m-d H:i' ,$value['time']);
        }
        return $this->pass($list);
    }

    public function setRemarkName($touserid = '', $name = '')
    {
        if (!$touserid || $touserid == $this->member['id']) {
            return $this->miss('编辑失败');
        }
        $ChatChargeRecordsMap = [
            'user_id' => $touserid,
            'another_id' => $this->member['id'],
        ];
        $ChatChargeRecordsField = 'user_remark';
        if ($this->member['id'] < $touserid) {
            $ChatChargeRecordsMap = [
                'user_id' => $this->member['id'],
                'another_id' => $touserid,
            ];
            $ChatChargeRecordsField = 'another_remark';
        }

        $timenow = time();
        $chat = Db::name('chat_charge_records')->where($ChatChargeRecordsMap)->find();
        $touser = Db::name('user')->find($touserid);
        $result = false;
        if ($chat) {
            $result = Db::name('chat_charge_records')->where(['id'=>$chat['id']])->update([$ChatChargeRecordsField => $name]);
        } else {
            $ChatChargeRecordsMap[$ChatChargeRecordsField] = $name;
            $ChatChargeRecordsMap['time'] = $timenow;
            $ChatChargeRecordsMap['payer'] = 0;
            $ChatChargeRecordsMap['state'] = 0;
            if ($this->member['yqr'] && $this->member['yqr'] == $touser['yqm']) {
                $ChatChargeRecordsMap['payer'] = $this->member['id'];
                $ChatChargeRecordsMap['state'] = 1;
            } else if ($this->member['yqm'] && $this->member['yqm'] == $touser['yqr']) {
                $ChatChargeRecordsMap['payer'] = $touserid;
                $ChatChargeRecordsMap['state'] = 1;
            }

            $result = Db::name('chat_charge_records')->insert($ChatChargeRecordsMap);
        }
        if ($result) {
            Gateway::sendToUid(getenv('SOCKET_PREFIX') . $this->member['id'], json_encode(['action' => 'api/Privatechat/changeChatPayer', 'touserid' => $touserid]));
            Gateway::sendToUid(getenv('SOCKET_PREFIX') . $touserid, json_encode(['action' => 'api/Privatechat/changeChatPayer', 'touserid' => $this->member['id']]));
            return $this->pass('编辑成功');
        }
        return $this->miss('编辑失败');
    }

    public function countStepsRecords($page = 1)
    {
        $user_id = $this->member['id'];
        $data = Db::name('count_steps_records')->where(['user_id'=>$user_id])->field('steps,distance,calorie,create_time')->order('create_time desc')->page($page)->limit(20)->select();
        foreach ($data as &$value) {
            $value['date'] = date('Y-m-d', $value['create_time']);
            $value['distance'] = intval($value['distance']);
            $value['calorie'] = intval($value['calorie']);
            unset($value['create_time']);
        }
        return $this->pass($data);
    }

    public function countSteps($steps = 0)
    {
        // $steps = 1002;
        if ($steps <= 0){
            return $this->miss('');
        }
        $config = Config::index('count_steps');
        if (!$config) {
            $config['count_steps_distance'] = 0.6;
            $config['count_steps_calorie'] = 0.045;
        }
        $timenow = time();
        $todayDate = date('Y-m-d');
        $today = Db::name('count_steps_records')->where(['user_id'=>$this->member['id']])->whereTime('create_time', 'today')->find();
        $data = [
            'steps'=>$steps,
            'distance'=>$steps*$config['count_steps_distance'],
            'calorie'=>$steps*$config['count_steps_calorie']
        ];
        if ($today) {
            if ($steps < $today['steps']) {
                return $this->miss('步数异常');
            }
            $data['update_time'] = $timenow;
            $result = Db::name('count_steps_records')
                        ->where(['id'=>$today['id']])
                        ->update($data);
        } else {
            $data['create_time'] = $timenow;
            $data['update_time'] = $timenow;
            $data['user_id'] = $this->member['id'];
            $result = Db::name('count_steps_records')
                        ->insert($data);
        }
        if ($result) {
            $flags = Db::name('user_flag')
                    ->where([
                        'user_id'=>$this->member['id'],
                        'start_date'=>['<=', $todayDate],
                        'paystate'=>1,
                        'status'=>0,
                        'end_time'=>['>', $timenow],
                        'signtime'=>['<', strtotime($todayDate)],
                        'steps'=>['>', 0]
                    ])
                    ->select();
            $keys = ['steps', 'distance', 'calorie'];
            foreach ($flags as $key => $value) {
                if ($value['steps'] <= $data[$keys[$value['steps_type']]]) {
                    action('api/Flag/autoSign', ['flag_id' => $value['id']]);
                }
            }
            return $this->pass('更新成功');
        }
        return $this->miss('更新失败');
    }

    public function systemLianmaiCheck($orderid, $state)
    {
        $data = Db::name('push_lianmai_system')->where(['user_id|touserid'=>$this->member['id'], 'order_id'=>$orderid, 'state'=>0])->find();
        if ($data) {
            if ($state == 1) {
                $msg = ['语音通话','视频通话'];
                $users = Db::name('user')->where(['id'=>['in', [$data['user_id'], $data['touserid']]]])->column('id', 'sex');
                Db::name('privatechat')->insert([
                    "userid" => $users['女'],
                    "touserid" => $users['男'],
                    "type" => $data['type'] + 9,
                    'second' => 0,
                    //'isRead' => 1,
                    'isCount' => 0,
                    'finish' => 1,
                    "content" => '[' . $msg[$data['type']] . ']',
                    'data' => json_encode(['orderid' => (string)$orderid]),
                    'order_id' => $orderid
                ]);
        
                // 更新会话列表
                ChatLists::updateLists($users['女'], $users['男'], 0, $data['type'] + 9);
            }
            Db::name('push_lianmai_system')->where(['id'=>$data['id']])->update(['state'=>$state]);
            return $this->pass(compact('state'));
        } else {
            return $this->miss('操作异常');
        }
    }

    public function rmFans($touid = 0)
    {
        $hasFans = Db::name('attention')->where(['to_user'=>$this->member['id'], 'user_id'=>$touid])->find();
        if (!$hasFans) {
            return $this->miss('暂无粉丝');
        }
        $res = Db::name('attention')->where(['id'=>$hasFans['id']])->delete();
        if ($res) {
            return $this->pass('移除成功');
        }
        return $this->miss('移除失败');
    }
    
    // 获取银行名称
	public function bankname()
	{
	    $bank=[
	        "中国农业银行","中国邮政储蓄银行","中国招商银行",
	        "中国工商银行","中国银行","华夏银行",
	        "浦发银行","中国建设银行","交通银行","上海银行",
	        "中国平安银行","中国民生银行",
	        "中国光大银行","北京银行","广发银行","兴业银行",
	        "中信银行","渤海银行","农村商业银行","浙商银行"
	    ];
	    return json(['code' => 200, 'msg' => '获取银行名称成功！','data'=>$bank]);
	}
}
